12

I am enforcing a unique constraint check in JPA for userid column which is enforced for all records in the user table.

@Table(name = "user",
       uniqueConstraints = @UniqueConstraint(columnNames = userid))

My requirement is that, the userid's within a particular organization needs to be unique and not across all organizations.

How do I enforce such a check?

Joe
  • 13,573
  • 28
  • 78
  • 142

1 Answers1

19

You can specify more than one field for your unique constraint, try:

 uniqueConstraints={@UniqueConstraint(columnNames={"userid", "organizationid"})}

By doing this, your constraint checks whether the combination of userid and organizationid is unique.

Best wishes, Fabian

halfdan
  • 32,443
  • 8
  • 76
  • 85
  • Appreciate your insights into this? Campus has OneToMany Buildings Building has OneToMany Rooms Room names needs to be unique within a campus. Would it be possible to define such a constraint on the Room entity? – Joe Dec 03 '09 at 11:22