jpa hibernate(1) 多对多,用户新增,只增加中间表对应角色关系,不增加角色role

用户user 角色role 中间表user_role,用户新增,只增加中间表对应角色关系,不增加角色role
只增加关联关系到中间表中,需要添加CascadeType.MERGE

User实体:
@ManyToMany(cascade = {CascadeType.MERGE})
@JsonIgnore
@JoinTable(name = "CMSUserRole",
        joinColumns = { @JoinColumn(name = "userid", referencedColumnName = "userid") },
    inverseJoinColumns = { @JoinColumn(name = "roleid", referencedColumnName = "roleid") })
private Collection roles;


Role实体:
@ManyToMany(mappedBy = "roles")
@Basic(fetch = FetchType.LAZY)
private Collection users;


controller中:
 @RequestMapping(value = "add",method= RequestMethod.POST)
@ResponseBody
public boolean register(User user){ 
    Role role=new Role();
    role.setId((long) 2);
    Set roles=new HashSet();
    roles.add(role);
    user.setRoles(roles) ;
    return userService.insert(user);
}

你可能感兴趣的:(java,web)