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

标签 java spring jpa foreign-keys 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) })

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

相关文章:

java - 使用 spring 和 tomcat 静态编织 eclipselink jpa

java - spring boot web socket 中的实时通知

java - 我在 JEE 套接字项目 SLF4J : Failed to load class "org.slf4j.impl.StaticLoggerBinder" 中遇到错误

java - 使用 GAE 任务队列处理持久性操作

java - 当我尝试删除 Activity 上的操作栏时,为什么会出现此异常?

java - 在 Eclipse JDT 中放置变量 1 上下文

java - Spring(规范)-如何创建具有多对多关系和集合的条件生成器

java - Hibernate 在 Spring 事务中抛出 TransactionRequiredException

验证错误: Value is not valid

java - JPA 合并与持久化