Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a unique key for two fields with Hibernate?

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.

like image 620
James Adams Avatar asked Jun 03 '09 18:06

James Adams


People also ask

How do I create a unique constraint in multiple columns?

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.

How do I make two columns unique in JPA?

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.

Can you have multiple unique keys?

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.

How do I make unique emails in spring boot?

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.


1 Answers

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.

like image 193
mtpettyp Avatar answered Sep 23 '22 03:09

mtpettyp