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

时间:2010-05-10 18:25:19

标签: java sql hibernate annotations

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

join b on a.id = b.a_id or b.a_id is null

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

有没有人有例子?

1 个答案:

答案 0 :(得分: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; }
}