如何返回特定类型的列表而不是List< Object []>在Hibernate?
问题描述:
我有课程树:
classA {
classB b;
classC c;
.....
}
我有这样的HQL查询:
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
此查询返回列表< Object []>
。
是可以将返回的数据强制转换为以下类:
Is it possible to cast the returned data to the following class:
classD {
Type1 fiedl1;
Type2 field2;
Type3 field3;
}
那么可以通过Hibernate进行投射还是我需要手动进行所有投射?
So can casting be made by Hibernate or I need manually do all casting?
答
JPA查询中有不同类型的选择。 您目前正在使用Array作为返回类型,您需要的是构造返回类型。以下是如何实现此目的:
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();
基本上有两件事:
- 自定义类必须是结果返回类型
- 自定义类必须有一个构造函数,它接受您在查询字符串中定义的结果值。