amungstudy
2023. 12. 14. 00:21
failed to lazily initialize a collection of role: personal.blog.entity.User.authorities: could not initialize proxy - no Session
오류 발생 해결하기
이번에 blog 프로젝트를 수정하면서 권한을 여러개 주기로 결정했다.
권한을 엔티티로 만들고, User와 권한을 일대다로 매핑하고
@OneToMany(mappedBy = "user")
List<Authorities> autorities = new ArrayList<>();
로 받아왔더니
spring security가 Login처리를 하는 과정에서 지연로딩 프록시 초기화가 불가능한 문제가 발생했다.
문제 해결과정 1)
Hibernate.initialize(authorities)메소드를
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
내에 적어봤지만 소용이 없다.
문제 해결과정2)
Hibernate5JakartaModule 를 이용해서 지연로딩 강제화를 해도 소용이 없다.
문제해결과정 3)
EAGER를 이용해서 해결하기는 싫었다. 따라서 Spring Security가 JPA를 이용해서 무슨 메서드를 이용해서 DB에서 User의 정보를 꺼내오는지 찾아보았다.
이미 내가 구현해놓은 인터페이스였다.
UserDetailService인터페이스를 구현하는 구현체에서 loadUserByUsername 메서드를 이용해서 사용자 이름을 기반으로 UserDetails 객체를 로드한다.
이때 이 메서드 내에서 구현해놓은 UserRepository의 메서드를 페치조인으로 수정해줬더니 문제가 해결되었다.
public class UserDetailService implements UserDetailsService {
private final UserRepository userRepository;
//email로 사용자 정보 가져온다
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
return userRepository.findByEmail(email)
.orElseThrow(()-> new IllegalArgumentException(email));
}
}
public interface UserRepository extends JpaRepository<User, Long> {
@Query("select u from User u join fetch u.authorities a where u.email = :email")
public Optional<User> findByEmail(@Param("email") String email);
}