[英]Hibernate Many-to-Many relation
I'm trying to implement Many-to-many relation using Hibernate and MySQL DB. 我正在尝试使用Hibernate和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. 当我尝试将新节点保存到数据库(已经有用户)时,它成功将新实体添加到“节点”表中,但是关系表“ users_nodes”为空。
This is the way I save Node entity: 这是我保存Node实体的方式:
@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. 您必须更新关联的所有者端( User.nodeList
),这意味着必须将User
与每个关联用户的Node
关联。 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 . 如果这是一个性能问题(如果User
的Nodes
很多,那么在将新节点与所需用户相关联时将它们全部加载会很昂贵),则可以更改映射,以使Node
是该关联的所有者和/或者您可以考虑此处介绍的其他选项和改进。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.