HQL return 列表<MyClass> 而不是列表<Object[]>
HQL return List<MyClass> instead 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")
我想要 return 它是:
List<MyObject>
而不是 List<Object[]>
我有这个class:
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
您可以使用 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;
}
为了使用自定义 class 我首先使用为这些属性创建一个构造函数
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")
您将 return 来自 MyObject 对象的列表
在我的 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")
我想要 return 它是:
List<MyObject>
而不是 List<Object[]>
我有这个class:
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
您可以使用 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;
}
为了使用自定义 class 我首先使用为这些属性创建一个构造函数
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")
您将 return 来自 MyObject 对象的列表