Hibernate : How to create a unique constraint for a table with annotation ?

Annotation

@Table(name = “tableName”, uniqueConstraints = @UniqueConstraint(name = “uniqueName”, columnNames = “columnName”))

Example:

If you want all emails of the user table are unique, so you can create:

 

@Table(name = "user", 
uniqueConstraints = @UniqueConstraint(name = "email_user_uc"
                                      ,columnNames = "email"))
public class User {

    @org.hibernate.validator.constraints.Email(message = "Invalid Email")
    @Size(max = 254, message = "It is too big")
    @Column @NotNull(message = "Please, set here the user email")
    private String email;

}

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s