如何使用注释指定列的组合应该是唯一约束? [英] How to specify that a combination of columns should be a unique constraint using annotations?
问题描述
我想确保表中的所有行都具有两个字段的唯一组合,并且我想在实体类中使用注释来指定这一点.我曾尝试使用 @Table 和 @UniqueConstraint 的组合,但显然我做错了,因为我似乎只能指定单独的列应该是唯一的(我已经可以指定使用 @Column 的唯一属性)而不是而不是列的组合.例如,我想要一个包含字段 A 和 B 的表只包含具有唯一 A 和 B 组合的行.两个字段/列都不需要是唯一的,两者的组合应该是唯一的.
I want to make sure that all rows in my table have a unique combination of two fields, and I want to specify this using annotations in my entity class. I have tried using a combination of @Table and @UniqueConstraint but apparently I'm doing it wrong, in that I can only seem to specify that the separate columns should be unique (I can already specify that using the @Column's unique property) rather than a combination of columns. For example I want a table which has fields A and B to contain only rows which have a unique combination of A and B. Neither field/column needs to be unique, it's the combination of the two which should be unique.
这是我迄今为止尝试过的,但没有任何乐趣:
Here's what I've tried so far with no joy:
@Table(name = "MY_TABLE",
uniqueConstraints = @UniqueConstraint(columnNames =
{ "FIELD_A", "FIELD_B" }))
和
@Table(name = "MY_TABLE",
uniqueConstraints = { @UniqueConstraint(columnNames =
{ "FIELD_A", "FIELD_B" }) })
有人可以建议正确的方法吗?此外,如果可以使用 JPA 注释而不是特定于 Hibernate 的注释,那会更好.
Can someone please suggest the right way to do this? Also if it's possible to use JPA annotations instead of Hibernate-specific annotations that'd be preferable.
预先感谢您的帮助.
--詹姆斯
推荐答案
第二次尝试
@Table(name = "MY_TABLE",
uniqueConstraints = { @UniqueConstraint(columnNames =
{ "FIELD_A", "FIELD_B" }) })
应该按预期工作.
这篇关于如何使用注释指定列的组合应该是唯一约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!