getNamedQuery with explicit custom class

那年仲夏 提交于 2019-12-25 05:33:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!