How to selectively retrieve items from a specific table via JPA

Environment: JPA 1, Hibernate 3.3.x

I have a JPA entity class (User), how I selectively fetch member variables (first_name, last_name) instead of fetching all custom attributes using the JPA api.

+2


a source to share


2 answers


If you are querying more columns, you will get an object result that you will need to apply to an array of objects to retrieve values. Your best bet is to create a viewObject class where you store the results directly:

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

      



where UserView looks like this:

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

      

+2


a source


You mean something like this (in which case the result of your query would be Object[]

):

SELECT u.firstName, u.lastName FROM User u

      

Alternatively, you can 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 NEW is not necessarily an entity, it just needs to provide the correct constructor.

+5


a source







All Articles