[英]How to save data with unique field in many-to-many relationship using JPA and Hibernate
I am new in hibernate and I have next situation: 我是休眠的新手,我遇到下一种情况:
@Entity
class Post {
@Id id;
@ManyToMany
@JoinTable(name = "ATag", joinColumns = @JoinColumn(name = "post_id"),
inverseJoinColumns = @JoinColumn(name = "tag_id"))
Set<Tag> tags;
}
@Entity
class Tag {
@Id Long id;
String name;
}
table tag
has constraint unique
on the name
field. 表
tag
在name
字段上具有unique
约束。 If I save post object with tag which name already exists it will return error like: 如果我用名称已经存在的标签保存帖子对象,它将返回如下错误:
Nov 25, 2014 9:23:13 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ERROR: duplicate key value violates unique constraint "tags_name_key"
Detail: Key (name)=(ert) already exists.
org.hibernate.exception.ConstraintViolationException: could not execute statement
how can I handle this situation? 我该如何处理这种情况?
You need to add the proper equals
and hashCode
implementations in your Tag
class. 您需要在
Tag
类中添加适当的equals
和hashCode
实现。 Using the name
property to distinguish between different Tags is a good idea. 使用
name
属性区分不同的Tag是一个好主意。
Since Post
. 自
Post
。 tags
is a Set
, it will discard duplicates prior to flushing the collection, so you shouldn't get the constraint violation. tags
是一个Set
,它将在刷新集合之前丢弃重复项,因此您不应该违反约束。
@Entity
public class Tag {
@Id Long id;
String name;
@Override
public int hashCode() {
HashCodeBuilder hcb = new HashCodeBuilder();
hcb.append(name);
return hcb.toHashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Tag)) {
return false;
}
Tag that = (Tag) obj;
EqualsBuilder eb = new EqualsBuilder();
eb.append(name, that.name);
return eb.isEquals();
}
}
Since the record you are trying to save already exists, you need to either call update or saveOrUpdate ... but that sort of depends on why you're trying to save a duplicate record in the first place? 由于您要保存的记录已经存在,因此您需要调用update或saveOrUpdate ...,但这取决于您为什么要首先保存重复的记录? Are you trying to insert or just update an existing record?
您是要插入还是仅更新现有记录?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.