gpt4 book ai didi

hibernate - 带有 HQL 的新对象

转载 作者:行者123 更新时间:2023-12-03 09:52:36 24 4
gpt4 key购买 nike

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

最佳答案

我认为该部分15.6. The select clause涵盖您要实现的目标:

15.6. The select clause

...

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

Or as a 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

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


在您的情况下,您可能想要:
SELECT new MyCustomList(product.code, SUM(product.price), COUNT(product.code))
from Product AS product
GROUP BY product.code

哪里 MyCustomList不一定是映射实体。

关于hibernate - 带有 HQL 的新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4027805/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com