为了账号安全,请及时绑定邮箱和手机立即绑定

HQL 返回 List<MyClass> 而不是 List<Object[]>

HQL 返回 List<MyClass> 而不是 List<Object[]>

汪汪一只猫 2023-08-04 19:17:56
打印我的 HQL:@Query("SELECT count(a.age) as age, count(w.weight) as weight from animals a inner join weight_table w on a.id = w.id")我想将其返回为: List<MyObject>而不是List<Object[]>我有这门课:public class MyObject {     private int age;     private int weight;     // getters setters all args constructor}是否可以使用如下方式在我的 HQL 中进行转换:SELECT new.com.cs.MyObject(age, weight) count(a.age) as age, count(w.weight) as weight from animals a inner join weight_table w on a.id = w.id
查看完整描述

2 回答

?
红颜莎娜

TA贡献1842条经验 获得超12个赞

您可以使用投影:


@Query("SELECT count(a.age) as age, count(w.weight) as weight from animals a inner join weight_table w on a.id = w.id")

public List<MyObject> myMethodNameDescribingFunctionality();

其中MyObject可能是一个接口:


public interface MyObject {

    @Value("#{target.age}")

    int age();


    @Value("#{target.weight}")

    int weight;

}


查看完整回答
反对 回复 2023-08-04
?
守着一只汪

TA贡献1872条经验 获得超3个赞

为了使用自定义类,我首先使用为这些属性创建一个构造函数


public class MyObject {

     private int age;

     private int weight;

     public  MyObject(int age , int weight) {

         this.age=age;

         this.weight = weight; 

     }

}

之后,在 hql 中你可以按照相同的值顺序调用这个构造函数


@Query("SELECT new com.packagename.MyObject(count(a.age), count(w.weight)) from animals a inner join weight_table w on a.id = w.id")

您将从 MyObject 对象返回一个列表


查看完整回答
反对 回复 2023-08-04
  • 2 回答
  • 0 关注
  • 90 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信