我在 ProductDfn 类中有一个像这样的 hibernate 映射
@ManyToOne( fetch = FetchType.LAZY, optional = true )
@JoinColumn( name = "productTypeFk", nullable = true )
public ProductType getProductType()
{
return productType;
}
请注意,该关系被定义为可选(并且该列可以为空)。
当做这样的 HQL 时
select p.name as col1, p.productType.name as col2 from ProductDfn p
内部连接用于将 ProductDfn 连接到 ProductType,因为 hibernate 从 select 子句中的隐式连接生成显式 SQL 连接。
但是,当 productType 为 null(在 DB 中)执行上述操作时,由于内部联接,不会返回任何行。对于这种关系,我希望 hibernate 默认执行外连接(因为这种关系是可选的),所以我会为 col2 返回“null”而不是根本没有行。
有谁知道这是否可能?
谢谢。
最佳答案
使用内部联接是因为您已明确列出 p.productType.name
在您的选择条款中。如果您只是选择 ProductDfn
,就不会发生这种情况因为您的提取设置为 LAZY
.
如果您只需要检索这两个属性,则必须在查询中显式指定外部联接:
select p.name as col1, ptype.name as col2
from ProductDfn p
left join fetch p.productType ptype
关于可空多对一的 Hibernate 默认加入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1525098/