I want to make sure that all rows in my table have a unique combination of two fields, and I want to specify this using annotations in my entity class. I have tried using a combination of @Table and @UniqueConstraint but apparently I'm doing it wrong, in that I can only seem to specify that the separate columns should be unique (I can already specify that using the @Column's unique property) rather than a combination of columns. For example I want a table which has fields A and B to contain only rows which have a unique combination of A and B. Neither field/column needs to be unique, it's the combination of the two which should be unique.
Here's what I've tried so far with no joy:
@Table(name = "MY_TABLE",
uniqueConstraints = @UniqueConstraint(columnNames =
{ "FIELD_A", "FIELD_B" }))
and
@Table(name = "MY_TABLE",
uniqueConstraints = { @UniqueConstraint(columnNames =
{ "FIELD_A", "FIELD_B" }) })
Can someone please suggest the right way to do this? Also if it's possible to use JPA annotations instead of Hibernate-specific annotations that'd be preferable.
Thanks in advance for your help.
--James
@UniqueConstraint Annotation. Annotation type UniqueConstraint specifies that a unique constraint is to be included in the generated DDL (Data Definition Language) for a table.
To define a UNIQUE on multiple columns, we put a comma-separated columns list inside parenthesis that follows the UNIQUE keyword.
@Column annotation is used for Adding the column the name in the table of a particular MySQL database.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint. However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
your second try
@Table(name = "MY_TABLE",
uniqueConstraints = { @UniqueConstraint(columnNames =
{ "FIELD_A", "FIELD_B" }) })
should work as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With