我在使用 spring hibernate 时遇到问题,当我更新用户时,这会删除关联的角色……这可能是级联问题吗?我已经尝试过各种级联配置......
人
@MappedSuperclass
public abstract class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column
private int id;
@OneToOne(cascade = { CascadeType.ALL } )
@JoinTable(name="user_roles",
joinColumns = {@JoinColumn(name="user_id", referencedColumnName="id")},
inverseJoinColumns = {@JoinColumn(name="role_id", referencedColumnName="id")}
)
.
.
.
}
角色
@Entity
@Table(name="roles")
public class Role {
@Id
@GeneratedValue
private Integer id;
private String authority;
@OneToMany(cascade = CascadeType.ALL )
@JoinTable(name="user_roles",
joinColumns = {@JoinColumn(name="role_id", referencedColumnName="id")},
inverseJoinColumns = {@JoinColumn(name="user_id", referencedColumnName="id")}
)
private Set<User> userRoles;
.
.
.
}
用户角色
@Entity
@Table (name = "user_roles")
public class UserRole {
@Id
@Column(name = "user_id")
private int userId;
@Column(name = "role_id")
private int roleId;
.
.
.
}
UserDaoImpl
@Override
public void updateUser(User user) {
try {
this.sessionFactory.getCurrentSession().update(user);
} catch (HibernateException e) {
System.out.println(e);
}
}
我得到这样的用户(已登录的用户):
@RequestMapping(value = "/edit/", method = RequestMethod.GET)
public String editUser(ModelMap map,Principal principal) {
try{
//Get logged in username
String loggedUserEmail = principal.getName();
User user = userService.getUserByEmail(loggedUserEmail);
map.addAttribute("user", user);
} catch(Exception e) {
log.error("/user/edit/---"+e);
}
return "forms/userForm";
}
然后我在用户表单上提交一些更改后尝试更新。
啊,我像这样插入 UserRole:
//Add userRole to db
UserRole userRole = new UserRole();
userRole.setUserId(user.getId());
userRole.setRoleId(1);
userRoleService.addUserRole(userRole);