hibernate. How to add unique index for field combination?
I think it will works :
@Table(name="UserPattern",
uniqueConstraints=
@UniqueConstraint(columnNames={"user_id", ""})
or
@Table(name="UserPattern", uniqueConstraints={
@UniqueConstraint(columnNames={"user_id", "patern_id"})
})
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;
...
}