Feras Odeh
Feras Odeh

Reputation: 9306

Using unique constraint on Hibernate JPA2

How can I implement my unique constraints on the hibernate POJO's? assuming the database doesn't contain any.

I have seen the unique attribute in @Column() annotation but I couldn't get it to work?
What if I want to apply this constraint to more than one column?

Upvotes: 24

Views: 60033

Answers (3)

Hons
Hons

Reputation: 4056

You can declare unique constraints using the @Table(uniqueConstraints = ...) annotation in your class

@Entity
@Table(uniqueConstraints=
           @UniqueConstraint(columnNames = {"surname", "name"})) 
public class SomeEntity {
    ...
}

Upvotes: 45

will824
will824

Reputation: 2244

In JPA2, you can add the Unique constraint directly to the field:

@Entity
@Table(name="PERSON_TABLE") 
public class Person{
  @Id
  @Column(name = "UUID")
  private String id;

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

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

IMHO its much better to assign the unique constraint directly to the attributes than at the beggining of the table.

If you need to declare a composite unique key however, then declaring it in the @table annotation is your only option.

Upvotes: 20

axtavt
axtavt

Reputation: 242786

Bascially, you cannot implement unique constraint without database support.

@UniqueConstraint and unique attribute of @Column are instructions for schema generation tool to generate the corresponsing constraints, they don't implement constraints itself.

You can do some kind of manual checking before inserting new entities, but in this case you should be aware of possible problems with concurrent transactions.

Therefore applying constraints in the database is the preferred choice.

Upvotes: 34

Related Questions