29

尝试从 HQL 查询创建对象,但无法弄清楚我做错了什么。

询问:

String query = "SELECT product.code, SUM(product.price), COUNT(product.code)
from Product AS product
GROUP BY product.code"

(或者我应该使用 new 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 框架

4

2 回答 2

53

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

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

WhereMyCustomList不一定是映射实体。

于 2010-10-26T21:52:54.843 回答
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));
于 2017-10-10T18:43:48.533 回答