[英]Hibernate - unique column constraint being ignored
I have a MySQL table to hold tags (ie like those used here on Stack Overflow). 我有一个MySQL表来保存标签(就像Stack Overflow上使用的那样)。 It simply has an id (pk) and a tag column to hold the tag itself. 它只有一个id(pk)和一个标记列来保存标记本身。
The annotated get methods for my Tag entity are shown below. 我的Tag实体的带注释的get方法如下所示。
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public int getId() {
return this.id;
}
@Column(name = "tag", unique = true, nullable = false)
public String getTag() {
return this.tag;
}
I am using a unique column constraint on tag as there should never be more than one row for a given tag. 我在标记上使用了唯一的列约束,因为给定标记永远不应该有多行。 However, Hibernate appears to be ignoring this, ie I can save the exact same tag many times and it simply creates a new row rather than throwing an exception. 但是,Hibernate似乎忽略了这一点,即我可以多次保存完全相同的标记,它只是创建一个新行而不是抛出异常。
Am I missing something or should this be working? 我错过了什么或者这应该有效吗?
From JavaDoc of UniqueConstraint
( unique=true
on @Colunm
is just a shortcut): 来自UniqueConstraint
JavaDoc( @Colunm
上的unique=true
只是一个快捷方式):
This annotation is used to specify that a unique constraint is to be included in the generated DDL for a primary or secondary table. 此批注用于指定将唯一约束包含在主表或辅助表的生成DDL中。
So it does not seem to enforce uniqueness upon inserts. 所以它似乎没有强制插入时的唯一性。 You should create a unique constraint in the database in any case. 在任何情况下,您都应该在数据库中创建唯一约束。
You miss that this is only a information. 你想念这只是一个信息。
You should add also constraint on the column in database. 您还应该在数据库中的列上添加约束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.