开发者

Hibernate - unique column constraint being ignored

开发者 https://www.devze.com 2023-01-23 10:09 出处:网络
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.

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.

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;
}开发者_高级运维

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.

Am I missing something or should this be working?


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

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.


You miss that this is only a information.

You should add also constraint on the column in database.

0

精彩评论

暂无评论...
验证码 换一张
取 消