Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 536
James Adams Avatar asked Aug 17 '10 16:08

James Adams


People also ask

Which of the following annotations can be used to specify unique Rdbms constraints in entity classes?

@UniqueConstraint Annotation. Annotation type UniqueConstraint specifies that a unique constraint is to be included in the generated DDL (Data Definition Language) for a table.

How do you make a unique two column combination?

To define a UNIQUE on multiple columns, we put a comma-separated columns list inside parenthesis that follows the UNIQUE keyword.

What is the use of @column annotation?

@Column annotation is used for Adding the column the name in the table of a particular MySQL database.

Can I define multiple unique constraints on a table?

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.


1 Answers

your second try

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

should work as expected.

like image 113
Tushar Tarkas Avatar answered Sep 27 '22 22:09

Tushar Tarkas