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.
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.
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.
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.
@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.
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.
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