Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JPA query.getResultList() to MY Objects

Tags:

java

jpa

jpql

I'm performing a Query to my DB in JPA. The Query "queries" 4 tables, and the result aggregates columns from that different tables.

My Query is something like:

Query query = em.createQuery("SELECT o.A, o.B, o.C, e.D, c.E FROM Table1 o, 
Table2 i, Table3 e, Table4 c WHERE o.X = i.X AND i.Y = e.Y AND i.Z = c.Z");

How can I get the query result and extract the different fields?

I created a class (MyObject) that represents each item of the result list, and I want to convert the query.getResultList() into a List< MyObject>.

How can I do it?

like image 747
user2144555 Avatar asked May 06 '14 16:05

user2144555


People also ask

Which query is executed by list getResultList ()?

getResultList executes the JPQL SELECT statement and returns the results as a List ; if no results are found then it returns an empty list.

How do you map native query results to entities?

The easiest way to map a query result to an entity is to provide the entity class as a parameter to the createNativeQuery(String sqlString, Class resultClass) method of the EntityManager and use the default mapping.

Can getResultList return null?

getResultList() returns an empty list instead of null . So check isEmpty() in the returned result, and continue with the rest of the logic if it is false. Save this answer.

What is query getSingleResult ()?

getSingleResult() Execute a SELECT query that returns a single untyped result. boolean.


2 Answers

This kind of query returns a List<Object[]>. So you just need a loop to convert each array into an instance of your class:

List<Object[]> rows = query.getResultList();
List<MyObject> result = new ArrayList<>(rows.size());
for (Object[] row : rows) {
    result.add(new MyObject((String) row[0],
                            (Long) row[1],
                            ...));
}
like image 183
JB Nizet Avatar answered Sep 18 '22 07:09

JB Nizet


You're looking for the SELECT NEW construct, explained in this answer:

"SELECT NEW your.package.MyObject(o.A, o.B, o.C, e.D, c.E) 
   FROM Table1 o, Table2 i, Table4 c
   WHERE o.X = i.X AND i.Y = e.Y AND i.Z = c.Z"

Of course, your MyObject must have a matching constructor.

like image 25
mabi Avatar answered Sep 19 '22 07:09

mabi