在我的总部:
@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
您可以使用投影:
@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 {
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 对象返回一个列表