简体   繁体   中英

Hibernate Many-to-Many relation

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!

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 User s 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM