1

I'm trying to implement Many-to-many relation using Hibernate and MySQL DB. I have class User:

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "users_nodes",
            joinColumns = {@JoinColumn(name = "user_id")},
            inverseJoinColumns = {@JoinColumn(name = "node_id")})
private List<Node> nodeList;

and class Node:

@ManyToMany(mappedBy = "nodeList", cascade = CascadeType.ALL)
private List<User> users;

When I'm trying to save a new Node to DB(which already have user in it) it successfully add new entity to "nodes" table, but relation table "users_nodes" is empty.

This is the way I save Node entity:

@Override @Transactional
public void persist(Node entity) {
    getCurrentSession().save(entity);
}

Thanks for your help!

1 Answers1

1

You have to update the owner side of the association (User.nodeList), meaning that you have to associate the User with the Node for each associated user. For example:

class Node {
  ...
  public void addUser(User user) {
    if (!users.contains(user)) {
      users.add(user);
      user.addNode(this);
    }
  }
}

class User {
  ...
  public void addNode(Node node) {
    if (!nodeList.contains(node)) {
      nodeList.add(node);
      node.addUser(this);
    }
  }
}

If this would be a performance issue (if Users have many Nodes so it would be expensive to load them all when associating a new node with the desired users), you could change your mappings so that Node is the owner of the association and/or you could consider other options and improvements described here.

Community
  • 1
  • 1
Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110