jpa,两个相互用@ManyToMany的实体,读取其中一个,就保存no session

User实体

    @ManyToMany(targetEntity = Role.class, fetch = FetchType.EAGER)
    @JoinTable(name = "USER_ROLE_RELATION", joinColumns = @JoinColumn(name = "userId"), inverseJoinColumns = @JoinColumn(name = "roleId"))
    public Set<Role> getRoles() {

        return roles;
    }

Role实体:

    @ManyToMany(targetEntity = User.class,mappedBy = "roles")
    public Set<User> getUsers() {
        return users;
    }

当读取 User的时候,就报错:

    @Transactional(readOnly = true)
    @Override
    public Page<User> loadAllUser(Integer pageNo) {

        PageRequest request = new PageRequest(pageNo - 1, 10);

        return userRepository.findAll(request);
    }
HTTP Status 500 - Could not write content: failed to lazily initialize a collection of role: domain.Role.users, could not initialize proxy - no Session (through reference chain: domain.Response["data"]->org.springframework.data.domain.PageImpl["content"]->java.util.UnmodifiableRandomAccessList[0]->domain.User["roles"]->org.hibernate.collection.internal.PersistentSet[0]->domain.Role["users"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: domain.Role.users, could not initialize proxy - no Session (through reference chain: domain.Response["data"]->org.springframework.data.domain.PageImpl["content"]->java.util.UnmodifiableRandomAccessList[0]->domain.User["roles"]->org.hibernate.collection.internal.PersistentSet[0]->domain.Role["users"])

怎么办?

阅读 3.5k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进