简体   繁体   English

如何修复休眠 JPA 中的 LazyInitializationException

[英]How to fix LazyInitializationException in hibernate JPA

There is a @ManyToMany table: User , user_role , roleuser .有一个@ManyToMany表: Useruser_roleroleuser

enter image description here在此处输入图片说明

The roleuser table contains roles: ROLE_USER , ROLE_ADMIN and others. roleuser表包含角色: ROLE_USERROLE_ADMIN等。

This is how I make the @ManyToMany tables relate to each other:这就是我使@ManyToMany表相互关联的方式:

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 .底线是我不想使用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:但是要做到这一点,我必须将FetchType.EAGER更改为FetchType.LAZY ,但是在这种情况下,当我添加用户时会发生一个众所周知的错误:

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嵌套异常是 org.hibernate.LazyInitializationException:未能延迟初始化角色集合:com.test.shop.model.user.Role.userList,无法初始化代理 - 没有会话

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);当您调用serviceJpa.saveRole(role);时,我认为您的代码是一种糟糕的模式serviceJpa.saveRole(role); jpa first loading roll.userList and adding user into it, then saving it's relation. jpa 首先加载 roll.userList 并将用户添加到其中,然后保存它的关系。 therefore , jpa first load roll.userList , but you set roll.userList load as lazy so jpa can not load userList beacuse your session closed!!!因此, jpa 首先加载 roll.userList ,但是您将 roll.userList 加载设置为惰性,因此 jpa 无法加载 userList 因为您的会话已关闭!!! please read this tutorial请阅读本教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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