Hibernate--忽略唯一的列约束 [英] Hibernate - unique column constraint being ignored

查看:184
本文介绍了Hibernate--忽略唯一的列约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MySQL表格来存放标签(即像Stack Overflow中使用的那些表格)。它只包含一个id(pk)和一个标签列来保存标签本身。

I have a MySQL table to hold tags (i.e. like those used here on Stack Overflow). It simply has an id (pk) and a tag column to hold the tag itself.

标记实体的注释get方法如下所示。

The annotated get methods for my Tag entity are shown below.

@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;
}

我在标签上使用了唯一的列约束,因为它永远不会超过给定标签一行。然而,Hibernate似乎忽略了这一点,也就是说我可以多次保存相同的标记,它只是创建一个新行,而不是抛出异常。

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, i.e. I can save the exact same tag many times and it simply creates a new row rather than throwing an exception.

我是否缺少

推荐答案

来自 UniqueConstraint unique = true on @Colunm 只是一个捷径):

From JavaDoc of UniqueConstraint (unique=true on @Colunm is just a shortcut):


注释用于指定在生成的主表或副表DDL中包含唯一约束。

This annotation is used to specify that a unique constraint is to be included in the generated DDL for a primary or secondary table.

似乎没有强制插入时的唯一性。无论如何,您应该在数据库中创建一个唯一的约束。

So it does not seem to enforce uniqueness upon inserts. You should create a unique constraint in the database in any case.

这篇关于Hibernate--忽略唯一的列约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆