一尘不染

HQL的新对象

hibernate

试图从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框架


阅读 231

收藏
2020-06-20

共1个答案

一尘不染

我认为第15.6select子句涵盖您要实现的目标:

15.6。选择子句

查询可以将多个对象和/或属性作为类型数组返回 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不一定是映射实体。

2020-06-20