Java 将 JPA query.getResultList() 转换为 MY Objects
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23500114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert JPA query.getResultList() to MY Objects
提问by user2144555
I'm performing a Query to my DB in JPA. The Query "queries" 4 tables, and the result aggregates columns from that different tables.
我正在JPA 中对我的数据库执行查询。查询“查询”4 个表,结果聚合来自不同表的列。
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>.
我创建了一个表示结果列表中每个项目的类 (MyObject),并且我想将 query.getResultList() 转换为 List< MyObject>。
How can I do it?
我该怎么做?
采纳答案by JB Nizet
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[]>
. 所以你只需要一个循环来将每个数组转换成你的类的一个实例:
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],
...));
}
回答by mabi
You're looking for the SELECT NEW
construct, explained in this answer:
您正在寻找这个答案中SELECT NEW
解释的构造:
"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.
当然,你MyObject
必须有一个匹配的构造函数。