所以我想添加一个使用两列的唯一约束。我在db中添加了唯一约束,我有以下Java代码
@Entity
@Table(
name = "test_table",
uniqueConstraints = @UniqueConstraint(
columnNames = {
"other_table_id",
"sort_order"
},
name = "my_unique_constraint")
)
class SomeTable {
private String label;
@ManyToOne(optional = false)
@JoinColumn(name = "other_table_id", nullable = false)
private OtherTable otherTable;
@NotNull
@Column(name = "sort_order", nullable = false)
private int sortOrder;
}
当我修改此表的排序并更新记录时,我得到了
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Duplicate entry '1-2' for key 'my_unique_constraint'
如何实施@UniqueConstraint
,以免出现此类错误。
答案 0 :(得分:1)
您收到此错误是因为您的uniqueConstraints未分开。
所以我的方法是将两个约束分开:
@Table(
name = "test_table",
uniqueConstraints = {
@UniqueConstraint(columnNames = "other_table_id"),
@UniqueConstraint(columnNames = "sort_order")
},
name = "my_unique_constraint")
)