开发者

How to selectively fetch items from a certain table via JPA

Environment: JPA 1, Hibernate 3.3.x

I have an JPA entity class (User), how do I selectively fetch member variables say (first_name, last_name) instead of fetching all user att开发者_高级运维ributes using the JPA api.


Do you mean something like this (and in that case, the result of your query will be an Object[]):

SELECT u.firstName, u.lastName FROM User u

Alternatively, you could use a constructor expression in the SELECT clause:

SELECT NEW com.acme.example.UserDetails(u.firstName, u.lastName) FROM User u

The class used in the NEW is not necessarily an Entity, it just has to provide a proper constructor.


If you query for more columns you'll get an object result which you'll have to cast to an object array to retrieve values. Better is to create a viewObject class in which you directly store the results:

select new full.package.name.UserView(u.firstName, u.LastName) from User u

where UserView looks like:

class UserView {
   String firstName, String lastName;
   // getters, setters/constuctor
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜