How to specify that a combination of columns should be a unique constraint using annotations?

James Adams picture James Adams · Aug 17, 2010 · Viewed 8.3k times · Source

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

Answer

Tushar Tarkas picture Tushar Tarkas · Aug 17, 2010

your second try

@Table(name = "MY_TABLE", 
   uniqueConstraints = { @UniqueConstraint(columnNames = 
                                           { "FIELD_A", "FIELD_B" }) })

should work as expected.