简体   繁体   中英

How to fix LazyInitializationException in hibernate JPA

There is a @ManyToMany table: User , user_role , roleuser .

enter image description here

The roleuser table contains roles: ROLE_USER , ROLE_ADMIN and others.

This is how I make the @ManyToMany tables relate to each other:

User.class

    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY)
    @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    public List<Role> getRoleList() {
        return roleList;
    }

Role.class

    @ManyToMany(mappedBy = "roleList", cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER)
    public List<User> getUserList() {
        return userList;
    }    



    public void addPerson(User user) {
        userList.add( user );
        user.getRoleList().add( this );
    }

And this is how I add the user:

AddUser.class

    User user = new User("Michael Joseph Jackson");

    Role role = serviceJpa.findRoleByRole("ROLE_USER");
    role.addPerson(user);

    serviceJpa.saveRole(role);

The bottom line is that I don't want to use fetch = FetchType.EAGER . One role can have thousands of users, and I don't want to get all thousand users when I access the role. But to do this, I have to change FetchType.EAGER to FetchType.LAZY , but then in this case, a well-known error occurs when I add a user:

Message Request processing failed; nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.test.shop.model.user.Role.userList, could not initialize proxy - no Session

I don't know what to do about it. Please tell me what am I doing wrong?

I thinking your code is a bad pattern, when you call serviceJpa.saveRole(role); jpa first loading roll.userList and adding user into it, then saving it's relation. therefore , jpa first load roll.userList , but you set roll.userList load as lazy so jpa can not load userList beacuse your session closed!!! please read this tutorial

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM