dlinx90
dlinx90

Reputation: 875

@UniqueConstraint for more than two columns

In my Spring/hibernate project I'm using uniqueConstraints = {@UniqueConstraint(columnNames={"ID_A", "ID_B"})} to validate a unique combination of columns in a table. This works fine when I only have two columns.

However when I want to add a third column ID_C to the constraint it no longer works.

  1. Does @UniqueConstraint only allow for two columns?
  2. If yes, then how would I validate the unique combination for more than two columns?

Thank you for the help, /D

Edit: What I mean by "it no longer works" is that no exception is thrown when I add a new entry to the table. With two columns it throws an ConstraintViolationException.

Upvotes: 0

Views: 1606

Answers (1)

Mikko Maunu
Mikko Maunu

Reputation: 42074

Adding UniqueConstraint alone to entity does not perform any validation. As said in the linked documentation, it gives instructions that are used in database schema generation:

Specifies that a unique constraint is to be included in the generated DDL for a primary or secondary table.

Now you have two options left:

  1. Let Hibernate to generate database schema
  2. Drop old constraint and add new by using SQL as usually.

Upvotes: 2

Related Questions