views:

114

answers:

2

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

+2  A: 

Looks correct to me. Similar question posted here

reverendgreen
See comment on Tushar's answer above. Thanks for the confirmation, your help is really appreciated!
James Adams
+2  A: 

your second try

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

should work as expected.

Tushar Tarkas
Thanks a lot for the help. It turns out that I had another error in my data insertion program which led me to believe that this was the issue. Now I've found the other error and this unique constraint is indeed working as advertised. I really appreciate your assistance!
James Adams
Even the first form should work.
Pascal Thivent