views:

38

answers:

2

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 attributes using the JPA api.

+4  A: 

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.

Pascal Thivent
thanks, the view seems to make the query interface much more understandable than the previous suggestion which lets you parse the output as an [Object[]] which would be much more problematic to maintain
Samuel
+1  A: 

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
}
Albert
thanks, the view seems to make the query interface much more understandable.
Samuel