Guru_1010
Guru_1010

Reputation: 574

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?

Upvotes: 5

Views: 2009

Answers (2)

Vlad Mihalcea
Vlad Mihalcea

Reputation: 153730

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();
    }
}

Upvotes: 1

bradleyfitz
bradleyfitz

Reputation: 691

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? Are you trying to insert or just update an existing record?

Upvotes: 0

Related Questions