关联时的Hibernate自定义连接子句

mys*_*mic 6 java sql annotations hibernate

我想将使用hibernate注释的2个实体与自定义连接子句相关联.该子句与通常的FK/PK相等,但也是FK为空的.在SQL中,这将是这样的:

join b on a.id = b.a_id or b.a_id is null
Run Code Online (Sandbox Code Playgroud)

根据我的阅读,我应该在所有者实体上使用@WhereJoinTable注释,但我很困惑我如何指定这个条件......特别是它的第一部分 - 指的是加入实体的id.

有人有例子吗?

Mat*_*ock 19

这是一个使用标准父/子范例的例子,我认为应该使用基本的@Where注释.

public class A {
  ...
  @ManyToOne(fetch = FetchType.EAGER) // EAGER forces outer join
  @JoinColumn(name = "a_id")
  @Where(clause = "a_id = id or a_id is null") // "id" is A's PK... modify as needed
  public B getB() { return b; }

}

public class B {
  ...
  @OneToMany(mappedBy = "b")
  public List<A> getA() { return a; }
}
Run Code Online (Sandbox Code Playgroud)

  • 当列“a_id”属于“B”时,如何在实体“A”中使用“@JoinColumn(name = "a_id")”? (2认同)