题
试图创建从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();
使用播放框架
解决方案
我认为 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
或者作为
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
不一定是映射的实体。
其他提示
我知道这是旧的文章,但你也可以使用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));
不隶属于 StackOverflow