Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple unique constraints in JPA

Is there a way to specify using JPA that there should be multiple unique constraints on different sets of columns?

@Entity @Table(name="person",         uniqueConstraints=@UniqueConstraint(columnNames={"code", "uid"})) public class Person {     // Unique on code and uid     public String code;     public String uid;      // Unique on username     public String username;      public String name;     public String email; } 

I have seen a hibernate specific annotation but I am trying to avoid vendor specific solutions as we are still deciding between hibernate and datanucleus.

like image 965
Jay Avatar asked Aug 04 '10 11:08

Jay


People also ask

Can I define multiple unique constraints on a table?

PRIMARY KEY constraint differs from the UNIQUE constraint in that; you can create multiple UNIQUE constraints in a table, with the ability to define only one SQL PRIMARY KEY per each table.

What is @UniqueConstraint?

A unique constraint is a type of column restriction within a table, which dictates that all values in that column must be unique though may be null.

How foreign key is defined in JPA entity?

Implementing With a Foreign Key in JPA. Note that we place the @OneToOne annotation on the related entity field, Address. Also, we need to place the @JoinColumn annotation to configure the name of the column in the users table that maps to the primary key in the address table.

What is @EmbeddedId?

@EmbeddedId is used for composite primary key. i.e. more than one column behaves jointly as primary key. We need to create an entity as Embeddable and the Embeddable entity can be embedded in other entity to achieve composite primary key. Person.java.


1 Answers

The @Table's attribute uniqueConstraints actually accepts an array of these. Your example is just a shorthand for an array with a single element. Otherewise it would look like:

@Table(name="person",  uniqueConstraints={    @UniqueConstraint(columnNames={"code", "uid"}),    @UniqueConstraint(columnNames={"anotherField", "uid"}) }) 

Whenever the unique constraint is based only on one field, you can use @Column(unique=true) on that column.

like image 134
Bozho Avatar answered Sep 21 '22 09:09

Bozho