每当我尝试将用户保存到MySql数据库时,它只会将数据保存到用户表,而不是 roles-user 和 role < / strong>表。一些帮助将不胜感激。
(每个用户都有多个角色,每个角色都可以属于多个用户)
我的数据库中有3个表:
users: (id,username)
roles_users: (user_id, role_id)
roles: (id,role)
后跟两个Hibernate实体:
这是我的用户模型:
@Entity(name = "users")
public class User{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String username;
@ManyToMany(mappedBy = "users", cascade = CascadeType.PERSIST)
private Set<Role> roles;
public Long getId() {
return id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Set<Role> getRoles() {
if (roles == null) {
roles = new HashSet();
}
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
这是我的角色模型:
@Entity(name = "roles")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "roles_users",
joinColumns = @JoinColumn(name = "role_id"),
inverseJoinColumns = @JoinColumn(name = "user_id"),
uniqueConstraints = {@UniqueConstraint(columnNames = {"role_id", "user_id"})})
private Set<User> users;
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<User> getUsers() {
if (users == null) {
users = new HashSet();
}
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
}
这是我用来保存用户及其角色的代码:
User user = new User();
Role role = new Role();
Set<User> userSet = new HashSet();
Set<Role> roleSet = new HashSet();
user.setUsername("Peter");
role.setName("ROLE_ADMIN");
userSet.add(user);
roleSet.add(role);
role.setUsers(userSet);
user.setRoles(roleSet);
userService.saveUser(user);
答案 0 :(得分:1)
您观察到这一点的原因是Role
是管理它与@ManyToMany
之间User
关系的实体,但您没有更新您的Role
对象码。我可能认为这是落后的,User
应该拥有这种关系。
如果您考虑一下,可以单独创建Role
个对象,然后将其分配给各种User
个对象,如代码所示。因此User
拥有这种关系是有意义的。
// Transaction 1
Role role = new Role( "ADMIN" );
session.save( role );
// Transaction 2
User user = new User( "Naros" );
user.getRoles().add( roleService.getRoleByName( "ADMIN" ) );
session.save( user );