spring-boot - 用户的 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:空
解决方案
User
和Role
类之间有@OneToMany 或@ManyToMany 关系
所以当你调用roleRepository.findAll()
它时返回一个角色列表,每个角色都有一个或多个用户,每个用户都有很多角色等等,这会导致无限循环。
所以要解决这个问题:你添加一个名为dto的其他层,这是一种避免 stackoverflow 错误的设计模式。
推荐阅读
- angular - 在不使用管道或方法的情况下,如何在 Angular 6 中为 null 时放置 0
- javascript - 赛普拉斯点击/触发未触发 eventListeners
- for-loop - 这个 for 循环的范围是多少?
- powerbi - 由于 X-Frame-Options,PowerBI Embedded 无法正常工作
- python - API 响应错误请求错误消息
- python - 如何标记唯一值?
- php - 如何在 WordPress 帖子上显示多个作者
- python - 如何在 Python 回归模型中合并和预测滞后时间序列变量
- javascript - 我的插件不适用于多个选择器
- python - Keras - “ValueError:检查目标时出错:预期activation_1具有形状(无,9)但得到形状为(9,1)的数组