将数据保存在多对多关系表中

时间:2019-07-01 11:57:15

标签: java spring hibernate many-to-many

主表具有ManyToMany批注:

@ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "user_role",
            joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id")})
    private List<Role> roles;

第二个:

@ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY)
    private List<User> users;

现在它是完美的并且可以完美地工作。但是当我想保存数据时:

 @Override
public void saveUser(User user) {

    Session currentSession = entityManager.unwrap(Session.class);

    Role role = getRoleByName(RoleName.ROLE_ADMIN);
    user.setRoles(Collections.singletonList(role));
    role.setUsers(Collections.singletonList(user));
    currentSession.saveOrUpdate(user);
}

public Role getRoleByName(RoleName name) {
    Session currentSession = entityManager.unwrap(Session.class);
    Query query = currentSession.createQuery("FROM Role where name =:name");
    query.setParameter("name", name);
    return (Role) query.uniqueResult();
}

数据未保存到数据库。也许我应该在saveUser方法中添加有关关系的信息。

0 个答案:

没有答案