CAPS LOCK
CAPS LOCK

Reputation: 2040

Hibernate JPA uniqueness

Let's say that this is a class that has unique constrained field.

@Entity
public class Thing {

   @Column(name = "name", unique = true)
   private String name;

   @ManyToOne
   private Owner owner;

}

Example works just fine if new Things are created with unique names. But when different owners want to create things with the same name this approach fails.

Is it possible to set unique constraint to differ records of Things in the database based on the Owners using Hibernate/JPA functionalities (I could not find any) or should I write my own logic and dump the unique from @Column.

Perhaps it could be done with Hibernate Validator? Reading the docs I haven't found much about unique constraints.

Upvotes: 1

Views: 93

Answers (1)

Michael Peacock
Michael Peacock

Reputation: 2104

You're looking for @UniqueConstraint

http://docs.oracle.com/javaee/5/api/javax/persistence/UniqueConstraint.html

Upvotes: 1

Related Questions