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

打印我的 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


汪汪一只猫
浏览 94回答 2
2回答

红颜莎娜

您可以使用投影:@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;}

守着一只汪

为了使用自定义类,我首先使用为这些属性创建一个构造函数public class MyObject {&nbsp; &nbsp; &nbsp;private int age;&nbsp; &nbsp; &nbsp;private int weight;&nbsp; &nbsp; &nbsp;public&nbsp; MyObject(int age , int weight) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.age=age;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.weight = weight;&nbsp;&nbsp; &nbsp; &nbsp;}}之后,在 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 对象返回一个列表
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java