繁体   English   中英

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

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

我有两个实体,分别称为 A 和 B。有一个关系实体 C 支持 A 和 B 之间的多对多关系。C 具有 A 的外键和 B 的外键,都标有 @ManyToOne 和@JoinColumn 注释。

我的用户希望系统强制为给定的 A 和 B 创建一个 C 记录,所以我想声明 A 外键和 B 外键的组合必须是唯一的。

我尝试在 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;
        ...

当我尝试 @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"}应该是columnNames = {"aId","bId"}

或者,如果这不能产生您正在寻找的结构,也许这个变体

@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