Hibernate默认加入可以为多对多 [英] Hibernate default joining for nullable many-to-one

查看:123
本文介绍了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作为来自ProductDfn的col2 p 

内部连接用于将ProductDfn连接到ProductType作为hibernate从select子句中的隐式连接生成显式SQL连接。

然而,当productType为null时(在DB中)执行上述操作时,不会返回任何行因为内连接。对于这种关系,我想让hibernate默认做一个外部联接(因为关系是可选的),所以我会为col2返回一个null,而不是根本没有行。



有人知道这是否可能吗?



谢谢。

解决方案 div>

使用内部连接是因为您在select子句中明确列出了 p.productType.name 。因为您的抓取设置为 LAZY ,所以您只需选择 ProductDfn 即可。



如果您只需要检索这两个属性,就必须在查询中显式地指定一个外连接:

  select p.name as col1,ptype.name as col2 
from ProductDfn p
left join fetch p.productType ptype


I have a hibernate mapping like this in a ProductDfn class

@ManyToOne( fetch = FetchType.LAZY, optional = true )
@JoinColumn( name = "productTypeFk", nullable = true )
public ProductType getProductType()
{
    return productType;
}

Note that the relationship is defined as optional (and the column is nullable).

When doing HQL something like this

select p.name as col1, p.productType.name as col2 from ProductDfn p

An inner join is used to join ProductDfn to ProductType as hibernate generates the explicit SQL join from the implicit join in the select clause.

However when doing the above when productType is null (in the DB) no row is returned because of the inner join. For this relationship I would like to have hibernate default to doing an outer join (because the relationship is optional) so I would get a "null" back for col2 rather than no row at all.

Does anyone know if this is possible?

Thanks.

解决方案

An inner join is used because you've explicitly listed p.productType.name in your select clause. This wouldn't have happened were you just to select ProductDfn since your fetch is set to LAZY.

If you only need to retrieve those two properties you'll have to explicitly specify an outer join in your query:

select p.name as col1, ptype.name as col2
  from ProductDfn p
  left join fetch p.productType ptype

这篇关于Hibernate默认加入可以为多对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆