Issue
I have two entities with many-to-many relationship.
in class Role:
@ManyToMany(mappedBy = "roles")
private Set<User> users = new HashSet<>();
and in class User:
@ManyToMany
@JoinTable(name = "role_user", joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
And I get the exception:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: User.roles, could not initialize proxy - no Session
When I add fetch = FetchType.EAGER
, I get another exception:
java.lang.StackOverflowError: null
and cycle between Role and User.
How can I resolve this problem? I saw similar questions on Stackoverflow, but I didn't find real worked solution for me.
UPD: Where the exception gets thrown:
@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;
}
}
...
Solution
It looks like @Transactional
doesn't work for an overridden method of AuthenticationProvider
. I should have created a separate service to handle this issue.
A similar answer here: https://stackoverflow.com/a/23652569/8253837
Answered By - Daria Pydorenko
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)