Java 关于关联的 Hibernate 自定义连接子句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2805322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate custom join clause on association
提问by mysomic
I would like to associate 2 entities using hibernate annotations with a custom join clause. The clause is on the usual FK/PK equality, but also where the FK is null. In SQL this would be something like:
我想使用休眠注释将 2 个实体与自定义连接子句相关联。该子句涉及通常的 FK/PK 相等,但也涉及 FK 为空的情况。在 SQL 中,这将类似于:
join b on a.id = b.a_id or b.a_id is null
From what I have read I should use the @WhereJoinTable annotation on the owner entity, but I'm puzzled about how I specify this condition...especially the first part of it - referring to the joining entity's id.
从我读过的内容来看,我应该在所有者实体上使用 @WhereJoinTable 注释,但我对如何指定这个条件感到困惑……尤其是它的第一部分 - 指的是加入实体的 id。
Does anyone have an example?
有人有例子吗?
采纳答案by Matt Brock
Here's an example using the standard parent/child paradigm that I think should work using the basic @Where annotation.
这是一个使用标准父/子范式的示例,我认为应该使用基本的 @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; }
}