尝试从HQL查询创建一个对象,但却无法弄清楚我做错了什么。
查询:
String query = "SELECT product.code, SUM(product.price), COUNT(product.code)
from Product AS product
GROUP BY product.code"
(或者我应该使用新的MyCustomList(product.code,SUM(...,即使它没有映射?) 现在我想将这个返回的列表转换为类似的对象:
class MyCustomList{
public String code;
public BigDecimal price;
public int total;
// Constructor
public MyCustomList(String code, String price, int total){ //...
检索数据:
// This throws ClassCastException
List<MyCustomList> list = MyClass.find(query).fetch();
使用Play框架
答案 0 :(得分:45)
我认为15.6. The select clause部分涵盖了您要实现的目标:
15.6. The select clause
...
查询可以返回多个对象 和/或作为类型数组的属性
Object[]
:select mother, offspr, mate.name from DomesticCat as mother inner join mother.mate as mate left outer join mother.kittens as offspr
或
List
:select new list(mother, offspr, mate.name) from DomesticCat as mother inner join mother.mate as mate left outer join mother.kittens as offspr
或者 - 假设班级
Family
有一个合适的构造函数 - 作为 实际的类型安全Java对象:select new Family(mother, mate, offspr) from DomesticCat as mother join mother.mate as mate left join mother.kittens as offspr
在您的情况下,您可能想要:
SELECT new MyCustomList(product.code, SUM(product.price), COUNT(product.code))
from Product AS product
GROUP BY product.code
MyCustomList
不一定是映射实体。
答案 1 :(得分:1)
我知道这是一篇旧帖子,但你也可以用于HQL:
Query query = session.createQuery("SELECT code AS code FROM Product");
或者这个用于SQL:
Query query = session.createSQLQuery("SELECT code AS code FROM Product");
使用:
query.setResultTransformer(Transformers.aliasToBean(MyCustomList.class));