Sunday, May 27, 2007

Java Persistence Query Returning Simple Custom Object

Consider the following situation: We needed to retrieve just a small fraction of information from the database about particular business objects and transmit this data over network. It is probably not very surprising that the following query:


Query q1 = em.createQuery("SELECT e.name, e.salary FROM Employee e");


returns List of Object[] instances. OK, what if we would like to return something much simpler then our original Employee object but still more concrete then general Object type? I found there is one very easy and effective solution:


Query q = em.createQuery(
"SELECT " +
"NEW mypackage.EmployeeDetail(e.id, e.name, e.salary) " +
"FROM Employee e");
List<EmployeeDetail> result = q.getResultList();


The mypackage.EmployeeDetail object is just POJO object with particular constructor without any JPA annotations or mapping file.

(Source: Michael Bouschen's Blog - Java Persistence Query Return Types)