简体   繁体   中英

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.

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.

I've tried to use the following annotation on the C table but get an error that they foreign keys listed do not exist.

@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:

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"}

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) })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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