Hibernate default joining for nullable many-to-one

故事扮演 提交于 2019-12-30 08:04:28

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/1525098/hibernate-default-joining-for-nullable-many-to-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!