I have two fields of an entity class which I don't want to be unique but to instead be used as composite fields for a key which must itself be unique. For example I have two fields (name and version) which can be the same for other records but together they must be unique. What is the best way to do that using Hibernate (with annotations)? I am using Hibernate Validator for other fields but I am not sure of a way to use that to validate that two fields together compose a unique key. I am using a generic entity class which has an id generic type which can be swapped out for a composite key class but I have yet to get that to work very well.
To define a UNIQUE constraint, you use the UNIQUE keyword followed by one or more columns. You can define a UNIQUE constraint at the column or the table level. Only at the table level, you can define a UNIQUE constraint across multiple columns.
A unique constraint can be either a column constraint or a table constraint. At the table level, we can define unique constraints across multiple columns. JPA allows us to define unique constraints in our code using @Column(unique=true) and @UniqueConstraint.
Key Differences Between Primary key and Unique key: A table can have only one primary key whereas there can be multiple unique key on a table.
Set unique = true on your property in your entity class. @Column(unique = true) private String userName; But this will not work with @valid, instead throw an exception on persistence. You have to use an appropriate logic to handle that.
This will create a unique key on the database:
@Table( name = "MYTABLE", uniqueConstraints = { @UniqueConstraint( columnNames = { "NAME", "VERSION" } ) } )
This will be enforced by the database on a update or persist.
You'd need to write your own custom validator if you wanted to enforce this using Hibernate Validator.
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