我有两个具有多对多关系的实体。如何在ManyToMany中使用FetchType.LAZY?
类角色:
@ManyToMany(mappedBy = "roles")
private Set<User> users = new HashSet<>();
,并在类用户:
@ManyToMany
@JoinTable(name = "role_user", joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
我得到异常:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: User.roles, could not initialize proxy - no Session
当我添加fetch = FetchType.EAGER
,我得到另一个异常:
java.lang.StackOverflowError: null
并在角色和用户之间循环。
我该如何解决这个问题?我在Stackoverflow上看到了类似的问题,但我没有找到真正有效的解决方案。
UPD: 在异常被抛出:
@Service
public class UserAuthenticationProvider implements AuthenticationProvider {
...
@Override
@Transactional
public Authentication authenticate(final Authentication authentication) {
final String login = authentication.getName();
final String password = authentication.getCredentials().toString();
final User user = userRepository.findByLogin(login);
if (user != null && passwordEncoder.matches(password, user.getPassword())) {
return new UsernamePasswordAuthenticationToken(login, password,
user.getRoles()); // problem here
} else {
return null;
}
}
...
我不相信问题出现在您提交的声明中。请提供一份[mcve],可以复制您报告的一项或两项例外情况。 –