Hibernate ManyToMany保存关系双方

时间:2014-10-16 22:55:47

标签: java hibernate hibernate-mapping

我在用户和角色之间有一个关系ManyToMany(成员是关系表)。我可以保存从角色到用户的关系,但不能保存用户到角色的关系。

User.java

@ManyToMany(fetch = FetchType.LAZY, mappedBy = "users")
public Set<Role> getRoles() {
    return roles;
}

public void setRoles(Set<Role> roles) {
    this.roles = roles;
}

Role.java

@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "members", catalog = "blackant_db", joinColumns = { @JoinColumn(name =     "user_id", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "role_id", nullable = false, updatable = false) })
public Set<User> getUsers() {
    return this.users;
}

public void setUsers(Set<User> users) {
    this.users = users;
}

当我将一组用户合并到一个角色中时,hibernate保存关系,否则hibernate只更新对象用户。 E.g:

RoleService

Role role = roleService.findById(1);
Set<User> currentUsers = role.getUsers();
roleDAO.clear();
currentUsers.addAll(users);
role.setUsers(currentUsers);
roleDAO.merge(role);
//This works, save the user relationship into table members

UserService

User user = userService.findById(1);
Set<Role> currentRoles = user.getRoles();
userDAO.clear();
currentRoles.addAll(roles);
user.setUsers(currentUsers);
userDAO.merge(user);
//This doesn't work, only save the user

如何在双方保存用户/角色组? 有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您是否尝试在User中添加cascade语句?

/ **  *(可选)必须级联到目标的操作  *该协会。  *  *

当目标集合是{@link java.util.Map时  * java.util.Map},cascade元素适用于  *地图价值。  *  *

默认为无级联操作。  * / CascadeType [] cascade()默认{};