在ManyToMany表,休眠,春季中保存数据的问题

时间:2019-07-01 20:20:48

标签: java spring hibernate many-to-many

下面-父表-用户:

if errorlevel NEQ 0 (
        echo ##teamcity[message text='failed' errorDetails='' status='ERROR']
        exit 1
)

下面您可以找到具有角色的表:

@Entity
@Table(name = "user")
public class User {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "username", length = 50, unique = true)
    @NotNull
    @Size(min = 4, max = 50)
    private String username;

    @Column(name = "password", length = 100)
    @NotNull
    @Size(min = 4, max = 100)
    private String password;

    @ManyToMany(cascade = { CascadeType.ALL }, 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;


//constructor, getters/setters

我将尝试通过以下方法保存用户:

@Entity
@Table(name = "role")
public class Role {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name", length = 50)
    @NotNull
    @Enumerated(EnumType.STRING)
    private RoleName name;

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

//constructor, getters/setters

但是我有两个问题: -首先-主要问题-我做错了事,无法保存新用户。 -第二个-我在getRoleByName的查询结果中没有null结果,但是当然,该角色存在于表user_roles中。

任何解决方案对我来说都是完美的。

谢谢。

1 个答案:

答案 0 :(得分:0)

好的,目前的情况非常酷!

@Override
    public void saveUser(User user) {
        Session currentSession = entityManager.unwrap(Session.class);
        Role role = getRoleByName(RoleName.ROLE_ADMIN);
        user.getRoles().add(role );
        role.getUsers().add( user );
        currentSession.persist(user);
    }

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

但是仍然不要保存到数据库。没有错误。有想法吗?