在我的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
答案 0 :(得分:1)
您可以使用projection:
@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;
}
答案 1 :(得分:0)
对于使用自定义类,我首先使用这些属性创建一个构造函数
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对象返回列表