Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 638
Guru_1010 Avatar asked Nov 10 '22 22:11

Guru_1010


1 Answers

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();
    }
}
like image 130
Vlad Mihalcea Avatar answered Nov 14 '22 22:11

Vlad Mihalcea