Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hibernate. How to add unique index for field combination?

I have following hibernate mapping:

@Entity
public class UserPattern {
    @Id
    @GeneratedValue
    Integer id;

    @ManyToOne
    @JoinColumn(name = "user_id")
    User user;

    @ManyToOne
    @JoinColumn(name = "patern_id")
    Pattern pattern;

    ...
}

Does hibernate allow to add unique index that combination of user and pattern was unique ?

like image 274
gstackoverflow Avatar asked Jul 10 '14 10:07

gstackoverflow


2 Answers

I think it will works :

@Table(name="UserPattern", 
    uniqueConstraints=
        @UniqueConstraint(columnNames={"user_id", ""})

or

@Table(name="UserPattern",  uniqueConstraints={
   @UniqueConstraint(columnNames={"user_id", "patern_id"})
})
like image 118
Keval Trivedi Avatar answered Oct 18 '22 20:10

Keval Trivedi


You may take a look at @NaturalId:

5.1.8. Natural-id

Although we recommend the use of surrogate keys as primary keys, you should try to identify natural keys for all entities. A natural key is a property or combination of properties that is unique and non-null. It is also immutable. Map the properties of the natural key as @NaturalId or map them inside the <natural-id> element. Hibernate will generate the necessary unique key and nullability constraints and, as a result, your mapping will be more self-documenting.

Note however, the clause about immutability - this may not suit your use-case.

@Entity
public class UserPattern {
  @Id
  @GeneratedValue
  Integer id;

  @ManyToOne
  @JoinColumn(name = "user_id")
  @NaturalId
  User user;

  @ManyToOne
  @JoinColumn(name = "patern_id")
  @NaturalId
  Pattern pattern;

  ...
}
like image 28
Greg Kopff Avatar answered Oct 18 '22 20:10

Greg Kopff