我有两个实体,称为 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) })
关于java - 有没有办法使单个 JPA 实体中两个外键的组合唯一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58820859/