HQL的新对象

Ind*_*rek 28 hibernate hql object playframework

试图从HQL查询创建一个对象,但只是无法弄清楚我做错了什么.

查询:

String query = "SELECT product.code, SUM(product.price), COUNT(product.code)
from Product AS product
GROUP BY product.code"
Run Code Online (Sandbox Code Playgroud)

(或者我应该使用新的MyCustomList(product.code,SUM(...,即使它没有映射?)现在我想将这个返回的列表转换为类似的对象:

class MyCustomList{
  public String code;
  public BigDecimal price;
  public int total;

  // Constructor
  public MyCustomList(String code, String price, int total){ //...
Run Code Online (Sandbox Code Playgroud)

检索数据:

// This throws ClassCastException    
List<MyCustomList> list = MyClass.find(query).fetch();
Run Code Online (Sandbox Code Playgroud)

使用Play框架

Pas*_*ent 47

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

15.6.select子句

...

查询可以将多个对象和/或属性作为类型数组返回 Object[]:

select mother, offspr, mate.name
from DomesticCat as mother
    inner join mother.mate as mate
    left outer join mother.kittens as offspr
Run Code Online (Sandbox Code Playgroud)

或者作为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
Run Code Online (Sandbox Code Playgroud)

或者 - 假设该类Family 具有适当的构造函数 - 作为实际的类型安全Java对象:

select new Family(mother, mate, offspr)
from DomesticCat as mother
    join mother.mate as mate
    left join mother.kittens as offspr
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您可能想要:

SELECT new MyCustomList(product.code, SUM(product.price), COUNT(product.code))
from Product AS product
GROUP BY product.code
Run Code Online (Sandbox Code Playgroud)

哪里MyCustomList不一定是映射的实体.

  • @Indrek:使用完全限定名:`select new com.acme.MyCustomList(...)from ...` (12认同)