24

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?

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
Feras Odeh
  • 9,136
  • 20
  • 77
  • 121

3 Answers3

45

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

@Entity
@Table(uniqueConstraints=
           @UniqueConstraint(columnNames = {"surname", "name"})) 
public class SomeEntity {
    ...
}
Hons
  • 3,804
  • 3
  • 32
  • 50
  • I tried to use it but eclipse unable to identify this annotation – Feras Odeh Dec 28 '10 at 12:59
  • Which one? The @UniqueConstraint? That one is coming from javax.persistence.UniqueConstraint – Hons Dec 28 '10 at 13:03
  • Have you added it using the annotation? What kind of DB are you using(If you have a visualization tool like pgadmin for postresql check if the constraint is on the table)? Did you use the logical names of the columns to define the constraint – Hons Dec 28 '10 at 13:36
  • 2
    Assuming id is already a primary key, this example is wrong. unique(id, name) is weaker than unique(id) and weaker than unique(name). A better example may be unique(name, surname). – Robert Hensing Jul 15 '13 at 09:50
34

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.

axtavt
  • 239,438
  • 41
  • 511
  • 482
20

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.

Johan
  • 74,508
  • 24
  • 191
  • 319
will824
  • 2,203
  • 4
  • 27
  • 29
  • Is this a unique contraint to a single column or is this a unique contraint to the combination of socialSecurityNumber and loginId? – Stephan Schielke Feb 22 '12 at 14:26
  • 13
    @StephanSchielke This creates a separate unique constraint for each column. To create a unique constraint on multiple fields, you need to use Hons' approach. – Naliba Sep 25 '12 at 19:19