Hibernate用户模型不保存用户角色和角色

时间:2016-08-05 16:56:20

标签: java mysql hibernate spring-mvc jpa

每当我尝试将用户保存到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);

1 个答案:

答案 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 );