Hibernate - 加入un相关对象

Cur*_*ind 8 hibernate hql

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

class Product{
int product_id;        
String name;
String description;
}
Run Code Online (Sandbox Code Playgroud)

Class Item{
int item_id;
String name;
String description;
int quantity;
int product_id; //Note that there is no composed product object.
}
Run Code Online (Sandbox Code Playgroud)

现在我想在p.product_id = i.item_id上执行类似select*from Product p left outer join Item i的查询

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

mer*_*ike 5

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

但是,当然您可以在映射文件中加入未映射为关联的内容.引用hibernate参考手册:

可以出现多个类,从而产生笛卡尔积或"交叉"连接.

from Formula, Parameter

from Formula as form, Parameter as param
Run Code Online (Sandbox Code Playgroud)

查询可以将多个对象和/或属性作为Object []类型的数组返回:

select mother, offspr, mate.name
from DomesticCat as mother
    inner join mother.mate as mate
    left outer join mother.kittens as offspr
Run Code Online (Sandbox Code Playgroud)

或者作为一个清单:

select new list(mother, offspr, mate.name)
from DomesticCat as mother
    inner join mother.mate as mate
    left outer join mother.kittens as offspr
Run Code Online (Sandbox Code Playgroud)

或者 - 假设类Family具有适当的构造函数 - 作为实际的类型安全Java对象:

select new Family(mother, mate, offspr)
from DomesticCat as mother
    join mother.mate as mate
    left join mother.kittens as offspr
Run Code Online (Sandbox Code Playgroud)

您可以使用as将别名分配给选定的表达式:

select max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n
from Cat cat
Run Code Online (Sandbox Code Playgroud)

当与选择新地图一起使用时,这非常有用:

select new map( max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n )
from Cat cat
Run Code Online (Sandbox Code Playgroud)

此查询将别名中的Map返回到选定值.

将其与简单的where子句相结合,我们得到:

select product, item
from Product product, Item item
where item.product_id = product.product_id
Run Code Online (Sandbox Code Playgroud)

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

select product, item
from Item item
left join item.product as product
Run Code Online (Sandbox Code Playgroud)


小智 3

这里有一个解决方法可以通过 hql 中的 ids 进行连接。

不过,我建议在这里使用本机 sql 查询。