JPA @JoinTable具有额外的连接条件 [英] JPA @JoinTable with extra join conditions
问题描述
我花了几个小时在四处搜寻,没有发现类似于我的情况的东西。
让我们假设以下多对多数据模型:
合约(任何商业实体)
- contract_id
- 其他字段
合约(另一商业实体)
- party_id
- 其他字段
Contract_Party(前两个
与附加角色指示符之间的关系,例如拥有者,签名者,卖主等)
- contract_id
- party_id
- 角色
现在让我们假设我想映射所有<与合约有关的合约(单向)。可以在 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> contract;
这很好。
但我在寻找的是如何将合约与特定角色
@OneToMany
@ ???(ROLE ='SIGNER')
private List< Contract> signedContracts;
技术上,我正在寻找一种方法来添加额外条件
转换为JOIN语句。到目前为止,在类似主题中发现以下想法: 谢谢!
您可以使用@WhereJoinTable注解。它适用于关联表
@OneToMany
@JoinTable(
name =Contract_Party,
joinColumns = {@JoinColumn(name =contract_id,referencedColumnName =contract_id)}
(name =party_id,referencedColumnName =party_id)},
}
@WhereJoinTable(ROLE ='SIGNER')
private List< Contract>合约;
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 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;
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 condition into JOIN statement.
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 :)
Thanks!
You can use @WhereJoinTable annotation. It applies to the association table
@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;
这篇关于JPA @JoinTable具有额外的连接条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!