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 ?
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;
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With