user63904
user63904

Reputation:

JPA - defining multi-column unique constraints

Is it possible using JPA to define multiple unique constraints.

@Entity
class Foo {
    long id;

     String name;

     MyEnum type;

}

Foo.id should be unique as should combinations of {Foo.name, Foo.type}.
Ex.
id, name, type
1, "name1", "type1"
2, "name1", "type2"
3, "name1", "type1" // error duplicate of id = 1

How do I achieve this using JPA annotations?

Thanks

Upvotes: 10

Views: 5327

Answers (1)

JB Nizet
JB Nizet

Reputation: 692121

With the uniqueConstraints attribute of the Table annotation:

@Table(name = "FOO", uniqueConstraints={
    @UniqueConstraint(columnNames = {"NAME", "TYPE"})
})

Upvotes: 16

Related Questions