Forkmohit
Forkmohit

Reputation: 753

How to update link table in Hibernate ManyToMany Mapping

I have a Hibernate ManyToMany mapping between data table and user table linked by data_user table. Now I want to update the data table to add one more user to the data. How to update link table(data_user) to add one more entry for the new user?

I, first updated the user collection: data.getUsers().add(user), and then in the DAO layer tried session.saveOrUpdate(data). But it deleted everything in the link table.


Update1: data_user(iddata_user,iddataroom,iduser) was manually created in the db.

Update2 : implemented Hashcode and equals for Data and User.

Update 3: I changed to CascadeType.MERGE. This updates my link table. Also, I am never going to update User table from Data which hibernate was trying when CascadeType was ALL.

org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session.

PS: I am very new to hibernate.

public class Data {
    private int dataId;
    private Data parentData;
    private Set<User> users;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = "data_user", joinColumns = { @JoinColumn(name = "iddata") },
        inverseJoinColumns = { @JoinColumn(name = "iduser") })
    public Set<User> getUsers() {
        return users;
    }
    ...
}

Upvotes: 1

Views: 783

Answers (1)

karim mohsen
karim mohsen

Reputation: 2254

You need to override equals() and hashCode() in your entities or you are going to run into issues sooner or latter see this for more details.

If your problem still exists after overriding equals() and hashCode() you may add a mappedBy on the other side of the relation see this for more details.

Upvotes: 1

Related Questions