首页 > 解决方案 > 用户的 findall () 角色存储库存在 StackOverflowError 问题。填充 data.sql

问题描述

数据是从 h2 数据库的 data.sql 脚本加载的。然后我想用 userRepository 获取所有用户。我做了 roleRepository.findAll() 但我有一个堆栈溢出错误。我正在尝试注册并登录。但是,当我提交注册表时,会出现 stackoverflow 错误。我认为错误是在 userRepository.findall () 级别,当数据库中有用户时它返回 null。

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public User save(User user) {
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        ArrayList<Role> roles = new ArrayList<Role>();
        roleRepository.findAll().forEach(role -> roles.add(role));
        user.setRoles(roles);
        return roleRepository.save(user);
    }
}

java.lang.StackOverflowError:空

标签: spring-bootjpaspring-security

解决方案


UserRole类之间有@OneToMany 或@ManyToMany 关系

所以当你调用roleRepository.findAll()它时返回一个角色列表,每个角色都有一个或多个用户,每个用户都有很多角色等等,这会导致无限循环。

所以要解决这个问题:你添加一个名为dto的其他层,这是一种避免 stackoverflow 错误的设计模式。


推荐阅读