gpt4 book ai didi

Hibernate - 加入不相关的对象

转载 作者:行者123 更新时间:2023-12-04 07:44:48 24 4
gpt4 key购买 nike

我有一个要求,其中我必须使用 Hibernate HQL 连接两个不相关的对象。
这是示例 POJO 类

class Product{
int product_id;
String name;
String description;
}


Class Item{
int item_id;
String name;
String description;
int quantity;
int product_id; //Note that there is no composed product object.
}

现在我想执行一个查询
select * from Product p left outer join Item i on p.product_id = i.item_id

我想要一个多维数组作为此查询的输出,以便我可以拥有 Product 和 Item 的单独实例,而不是组合在另一个实例中。
有没有办法在 Hibernate 中做到这一点?

最佳答案

通过存储关联对象的 id 而不是关联对象本身来表示对象之间的关联是不常见的。存储对象更具表现力和类型安全,并且不需要对性能产生影响,因为 hibernate 具有延迟加载代理。

但当然,您可以在映射文件中加入未映射为关联的事物。引用 hibernate reference manual :

Multiple classes can appear, resulting in a cartesian product or "cross" join.

from Formula, Parameter

from Formula as form, Parameter as param


and

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

You can assign aliases to selected expressions using as:

select max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n
from Cat cat

This is most useful when used together with select new map:

select new map( max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n )
from Cat cat

This query returns a Map from aliases to selected values.



结合一个简单的 where 子句,我们得到:
select product, item
from Product product, Item item
where item.product_id = product.product_id

编辑 :我错过了你想要一个外连接。在这种情况下,我不知道除了映射关联之外的其他方法,因此您可以对其进行普通连接。请注意,这不需要特定形式的查询结果,即您仍然可以执行以下操作:
select product, item
from Item item
left join item.product as product

关于Hibernate - 加入不相关的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4533790/

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