java 带有额外连接条件的 JPA @JoinTable
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27945738/
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
JPA @JoinTable with extra join conditions
提问by Vitaljok
I have spent couple of hours searching around and did not found anything similar to my case.
我花了几个小时四处寻找,但没有找到与我的情况类似的东西。
Let's assume following many-to-many data model:
让我们假设以下多对多数据模型:
Contract (any business entity) - contract_id - other fields Party (another business entity) - party_id - other fields Contract_Party (relations between first two with additional role indicator, e.g. owner, signer, seller, etc) - contract_id - party_id - role
Now let's assume I want to map allcontracts related to party (uni-directional). It can be done using following annotations in Party
entity class:
现在让我们假设我想映射与参与方(单向)相关的所有合同。可以使用Party
实体类中的以下注释来完成:
@OneToMany
@JoinTable(
name="Contract_Party",
joinColumns = {@JoinColumn(name="party_id", referencedColumnName="party_id")},
inverseJoinColumns = {@JoinColumn(name="contract_id", referencedColumnName="contract_id")}
}
private List<Contract> contracts;
That is fine.
没事儿。
But what I'm looking for is how to map contracts with particular role?
但我正在寻找的是如何映射具有特定角色的合同?
@OneToMany
@??? ( "ROLE = 'SIGNER' ")
private List<Contract> signedContracts;
Technically I'm looking for a way to add extra conditioninto JOIN statement.
从技术上讲,我正在寻找一种向 JOIN 语句添加额外条件的方法。
So far found following ideas in similar topics:
到目前为止,在类似主题中发现了以下想法:
- map join table as separate entity, and perform filtering by role using custom queries;
- Hibernate has @JoinFormula annotation, but no way to apply it inside @JoinTable;
- Hibernate also has @Where annotation, but it adds condition for Contract table not for join table;
- use @MapKeyColumn and return Map instead of List, but I can have multiple contracts per one role;
- create a view on DB side (this one works indeed :)
- 将连接表映射为单独的实体,并使用自定义查询按角色执行过滤;
- Hibernate 有@JoinFormula 注释,但无法在@JoinTable 中应用它;
- Hibernate 也有@Where 注释,但它为合同表而不是连接表添加了条件;
- 使用@MapKeyColumn 并返回 Map 而不是 List,但我可以为一个角色拥有多个合同;
- 在 DB 端创建一个视图(这个确实有效:)
Thanks!
谢谢!
回答by jjbravo
You can use @WhereJoinTable annotation. It applies to the association table
您可以使用@WhereJoinTable 注释。它适用于关联表
@OneToMany
@JoinTable(
name="Contract_Party",
joinColumns = {@JoinColumn(name="party_id",referencedColumnName="party_id")},
inverseJoinColumns = {@JoinColumn(name="contract_id", referencedColumnName="contract_id")}
}
@WhereJoinTable ( "ROLE = 'SIGNER' ")
private List<Contract> contracts;
回答by Thiago Araújo
You must use:
您必须使用:
@WhereJoinTable(clause = "ROLE ='SIGNER'")