如何返回特定类型的列表而不是List< Object []>在Hibernate? [英] How to return a list of specific type instead of List<Object[]> in Hibernate?

查看:248
本文介绍了如何返回特定类型的列表而不是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();

基本上有两件事:


  1. 自定义类必须是结果返回类型

  2. 自定义类必须有一个构造函数,它接受您在查询字符串中定义的结果值。

阅读有关JPA2查询中的选择的更多信息。

这篇关于如何返回特定类型的列表而不是List&lt; Object []&gt;在Hibernate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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