85

Is there a way to specify using JPA that there should be multiple unique constraints on different sets of columns?

@Entity
@Table(name="person", 
       uniqueConstraints=@UniqueConstraint(columnNames={"code", "uid"}))
public class Person {
    // Unique on code and uid
    public String code;
    public String uid;

    // Unique on username
    public String username;

    public String name;
    public String email;
}

I have seen a hibernate specific annotation but I am trying to avoid vendor specific solutions as we are still deciding between hibernate and datanucleus.

Jay
  • 19,649
  • 38
  • 121
  • 184

1 Answers1

137

The @Table's attribute uniqueConstraints actually accepts an array of these. Your example is just a shorthand for an array with a single element. Otherewise it would look like:

@Table(name="person",  uniqueConstraints={
   @UniqueConstraint(columnNames={"code", "uid"}),
   @UniqueConstraint(columnNames={"anotherField", "uid"})
})

Whenever the unique constraint is based only on one field, you can use @Column(unique=true) on that column.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 3
    I currently have this annotation, but it seems like Hibernate is not generating the index for the table whether the table already exists (and it's set to update) or if I remove the table and let Hibernate automatically generate it. Am I missing something? – Kevin M Sep 26 '14 at 19:32