如何返回对象类型而不是List< Object []>在hibernate?
问题描述:
我有类树:
classA {
classB b;
classC c; .....
}
我有hql查询像:
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
此查询返回List。可以使用hibernate来投射
This query returns List. Does it possible to cast using hibernate to e.g.
classD {
Type1 fiedl1;
Type2 field2;
Type3 field3;
}
所以铸造将由hibernate或需要手动做所有铸造?
谢谢。
so casting will be made by hibernate or need manually do all casting? Thanks.
答
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();
基本上有两件事:
- 自定义类必须是您的结果返回类型
- 自定义类必须有一个构造函数, / li>
- Custom class must be your results return type
- Custom class must have a constructor which takes result values you define in query string.