Convert JPA query.getResultList() to MY Objects

江枫思渺然 提交于 2020-02-21 11:47:30

问题


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?


回答1:


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],
                            ...));
}



回答2:


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.



来源:https://stackoverflow.com/questions/23500114/convert-jpa-query-getresultlist-to-my-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!