带有 HQL 的新对象 [英] New object with HQL
问题描述
尝试从 HQL 查询创建对象,但无法弄清楚我做错了什么.
Trying to create an object from an HQL query, but just can't figure out what i'm doing wrong.
查询:
String query = "SELECT product.code, SUM(product.price), COUNT(product.code)
from Product AS product
GROUP BY product.code"
(或者我应该使用 new MyCustomList(product.code, SUM(... ,即使它没有被映射?)现在我想把这个返回的列表转换成一个类似的对象:
(or should I use new MyCustomList(product.code, SUM(... , even though it's not mapped?) Now I want to cast this returned list into a similar object:
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 框架
推荐答案
我认为 15.6.select 子句涵盖了您要实现的目标:
I think that the section 15.6. The select clause covers what you're trying to achieve:
...
查询可以返回多个对象和/或属性作为类型数组对象[]
:
Queries can return multiple objects
and/or properties as an array of type
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 对象:
Or - assuming that the class Family
has an appropriate constructor - as an
actual typesafe Java object:
select new Family(mother, mate, offspr)
from DomesticCat as mother
join mother.mate as mate
left join mother.kittens as offspr
就您而言,您可能想要:
In your case, you probably want:
SELECT new MyCustomList(product.code, SUM(product.price), COUNT(product.code))
from Product AS product
GROUP BY product.code
其中 MyCustomList
不一定是映射实体.
Where MyCustomList
is not necessarily a mapped entity.
这篇关于带有 HQL 的新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!