简体   繁体   English

有没有办法使单个 JPA 实体中的两个外键组合唯一?

[英]Is there a way to make the combination of two foreign keys in a single JPA entity unique?

I have two entities call them A and B. There is a relationship entity C that supports a many-to-many relationship between A and B. C has a foreign key to A and a foreign key to B both marked with a @ManyToOne and @JoinColumn annotation.我有两个实体,分别称为 A 和 B。有一个关系实体 C 支持 A 和 B 之间的多对多关系。C 具有 A 的外键和 B 的外键,都标有 @ManyToOne 和@JoinColumn 注释。

My user wants the system to enforce that only one C record can be created for a given A and B so I'd like to declare that the combination of the A foreign key and the B foreign key must be unique.我的用户希望系统强制为给定的 A 和 B 创建一个 C 记录,所以我想声明 A 外键和 B 外键的组合必须是唯一的。

I've tried to use the following annotation on the C table but get an error that they foreign keys listed do not exist.我尝试在 C 表上使用以下注释,但出现错误,列出的外键不存在。

@Table(uniqueConstraints=@UniqueConstraint(name = "UIDX_a_b", columnNames = {"aId, bId"}))
@Entity
@Table(uniqueConstraints=@UniqueConstraint(name = "UIDX_a_b", columnNames = {"aId, bId"}))
public class C{
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    @ManyToOne(optional=false)
    @JoinColumn(name="aId")
    private A a;
    @ManyToOne(optional=false)
    @JoinColumn(name="bId")
    private B b;
        ...

When I tried to @Table annotation, I get the following error:当我尝试 @Table 注释时,我收到以下错误:

Caused by: org.hibernate.AnnotationException: Unable to create unique key constraint (aId, bId) on table C: database column 'aId, bId' not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)

columnNames = {"aId, bId"} should probably be columnNames = {"aId","bId"} columnNames = {"aId, bId"}应该是columnNames = {"aId","bId"}

Or if that's not producing quite the structure you're looking for, perhaps this variant或者,如果这不能产生您正在寻找的结构,也许这个变体

@Table(indexes = { @Index(name = "UIDX_a_b",  columnList="aId,bId", unique = true) })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM