10

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

boutta
  • 24,189
  • 7
  • 34
  • 49

1 Answers1

16

With the uniqueConstraints attribute of the Table annotation:

@Table(name = "FOO", uniqueConstraints={
    @UniqueConstraint(columnNames = {"NAME", "TYPE"})
})
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 1
    Oracle will report a column not found if the property does not have its column name attribute explicitly specified in the Column annotation. – Stephane Oct 22 '14 at 09:53