我花了几个小时四处搜索,但没有发现任何与我的情况相似的东西。
让我们假设遵循多对多数据模型:
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 all contracts related to party (uni-directional). It can be done using following annotations in Party
entity class:
@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;
没关系。
但我正在寻找的是如何将契约(Contract)映射到特定角色?
@OneToMany
@??? ( "ROLE = 'SIGNER' ")
private List<Contract> signedContracts;
从技术上讲,我正在寻找一种将额外条件添加到 JOIN 语句中的方法。
到目前为止在类似主题中发现了以下想法:
- 将联接表映射为单独的实体,并使用自定义查询按角色执行过滤;
- Hibernate 有@JoinFormula 注释,但无法在@JoinTable 中应用它;
- Hibernate 也有@Where 注解,但它为Contract 表添加了条件,而不是为join 表添加了条件;
- 使用@MapKeyColumn 并返回 Map 而不是 List,但我可以为每个角色分配多个契约(Contract);
- 在数据库端创建一个 View (这个确实有效:)
谢谢!
最佳答案
您可以使用@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;
关于java - 具有额外连接条件的 JPA @JoinTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27945738/