如何返回特定类型的列表而不是 List<Object[]>在休眠中? [英] How to return a list of specific type instead of List<Object[]> in Hibernate?
本文介绍了如何返回特定类型的列表而不是 List<Object[]>在休眠中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有类树:
classA {B级;C级;.....}
我有这样的 HQL 查询:
SELECT a.field1, b.field2, c.field3, c.field4从左外连接 b 上 a.id = b.fk左外连接 c on b.id = c.fk
此查询返回List
.
是否可以将返回的数据转换为以下类:
classD {类型 1 字段 1;类型 2 字段 2;Type3 field3;}
那么可以通过 Hibernate 进行投射还是我需要手动进行所有投射?
解决方案
JPA 查询中有不同类型的选择.您当前使用的是 Array 作为返回类型,您需要的是 Construct 返回类型. 这是如何实现的:
String queryStr =选择新的包.YourDefinedCustomClass(a.field1, b.field2, c.field3, c.field4) 来自左外连接 b在 a.id=b.fk 上左外连接 c 在 b.id=c.fk 上";TypedQuery查询 =em.createQuery(queryStr, YourDefinedCustomClass.class);List结果 = query.getResultList();
基本上有两件事:
- 自定义类必须是您的结果返回类型
- 自定义类必须有一个构造函数,它接受您在查询字符串中定义的结果值.
I have tree of classes:
classA {
classB b;
classC c;
.....
}
I have HQL query like this:
SELECT a.field1, b.field2, c.field3, c.field4
FROM a LEFT OUTER JOIN b ON a.id = b.fk
LEFT OUTER JOIN c ON b.id = c.fk
This query returns List<Object[]>
.
Is it possible to cast the returned data to the following class:
classD {
Type1 fiedl1;
Type2 field2;
Type3 field3;
}
So can casting be made by Hibernate or I need manually do all casting?
解决方案
There are different types of selects in JPA queries. You are currently using Array as a return type, what you need is Construct return type. Here is how to achieve this:
String queryStr =
"select NEW package.YourDefinedCustomClass(
a.field1, b.field2, c.field3, c.field4) from a left outer join b
on a.id=b.fk left outer join c on b.id=c.fk";
TypedQuery<YourDefinedCustomClass> query =
em.createQuery(queryStr, YourDefinedCustomClass.class);
List<YourDefinedCustomClass> results = query.getResultList();
Basically there are two things:
- Custom class must be your results return type
- Custom class must have a constructor which takes result values you define in query string.
Read more on selects in JPA2 queries.
这篇关于如何返回特定类型的列表而不是 List<Object[]>在休眠中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文