0

Say I have a Person model (Java class and Database table) which has columns/fields like name, age, gender, height, weight.

Now there are 2 possibilities

1) I would need the entire column data..so i would have the named query as;

@NamedQuery(name = "Person.findAll", query = "Select p from Person WHERE ..."

2) I need only specific column data..so i would have the named query as;

@NamedQuery(name = "Person.findSpecific", query = "Select p.name, p.age from Person WHERE ..."

In the first case, if I call/execute the named query as;

Query query = getNamedQuery("Person.findAll");

it automatically maps the response to the Person Java class. But in the 2nd case (specific columns), it does not. It shows the response as Vector with Object array.

My question is is there any explicit way of making the query response map automatically to my custom class when I am using the specific column query

I have already tried

Query query = getNamedQuery("Person.findSpecific",Person.class);

But that again does not map it to Person class.

copenndthagen
  • 49,230
  • 102
  • 290
  • 442

1 Answers1

2

You can use constructor expressions in the select clause of any JPA query:

select new my.app.PersonView(p.name, p.age) from Person p ...

In this case, for every line in the result, a new PersonView instance is created.

Note that this instances are NOT connected to the data source (they are not managed), so you will not be able to change the underlying data by modifying the instances.

That's why I suggest to NOT use entity classes in constructor expressions to not mix them up with 'real' entities. Instead write custom 'transfer objects' that only carry the data. Either one tailored class per projection or - if many different projections on the same entity are required - one bigger class with multiple constructors that is used for all projections. In that case, some fields will always be empty.

isnot2bad
  • 24,105
  • 2
  • 29
  • 50
  • So if I need multiple combinations of columns to return ...should I need to create new class for each combination ? – copenndthagen Nov 20 '13 at 07:50
  • It depends (as so often). If you only have two or three projections think of custom classes. If you have really different combinations (e.g. name+age, name+city, city+age, ...) write one custom class that you use for all and document it so that it's clear that not all properties will be set in every query. But I suggest to not use Person class itself in constructor expressions to not mix them up with real Person entities. – isnot2bad Nov 20 '13 at 08:00