问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/20090094/getnamedquery-with-explicit-custom-class