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. 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. Using the name
property to distinguish between different Tags is a good idea.
Since Post
.tags
is a Set
, it will discard duplicates prior to flushing the collection, so you shouldn't get the constraint violation.
@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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With