Defining the Column Constraints
Whenever the unique constraint is based only on one field, we can use @Column(unique=true) on that column.
Let's define a unique constraint on the personNumber field:
@Column(unique=true)
private Long personNumber;
When we execute the schema creation process, we can validate it from the logs:
[main] DEBUG org.hibernate.SQL -
alter table Person add constraint UK_d44q5lfa9xx370jv2k7tsgsqt unique (personNumber)
Defining Unique Constraints
JPA helps us to achieve that with the @UniqueConstraint annotation. We do that in the @Table annotation under the uniqueConstraints attribute. Let's remember to specify the names of the columns:
@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "personNumber", "isActive" }) })
We can validate it once the schema is generated:
[main] DEBUG org.hibernate.SQL -
alter table Person add constraint UK5e0bv5arhh7jjhsls27bmqp4a unique (personNumber, isActive)