将JPA query.getResultList()转换为MY对象 [英] Convert JPA query.getResultList() to MY Objects

查看:173
本文介绍了将JPA query.getResultList()转换为MY对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JPA 对我的数据库执行查询.查询查询" 4个表,结果汇总来自该不同表的列.

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

我的查询类似于:

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?

我创建了一个代表结果列表的每个项目的类(MyObject),并且我想将query.getResultList()转换为List< MyObject> .

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>.

我该怎么办?

推荐答案

这种查询返回List<Object[]>.因此,您只需要一个循环即可将每个数组转换为类的实例:

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

这篇关于将JPA query.getResultList()转换为MY对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆