
Spring Security를 공부하던 중 발생한 에러
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role:
spring_security.jwt.domain.Member.roles: could not initialize proxy - no Session
public class Member {
...
@ElementCollection(fetch = FetchType.LAZY)
@Enumerated(EnumType.STRING)
private List<Role> roles = new ArrayList<>();
...
}
Member 엔티티에서 roles가 지연로딩으로 설정됨!!
방법 1. fetch 전략 수정
@ElementCollection(fetch = FetchType.EAGER)
즉시로딩으로 변경하면 회원 조회 시 roles도 함께 로드되어서 해결 가능
단, Member를 조회하는 모든 쿼리가 항상 roles 테이블을 JOIN
-> 불필요한 join으로 성능 저하될 수도..
방법 2. FetchType.LAZY 설정을 유지 + JOIN FETCH
@Query("SELECT m FROM Member m JOIN FETCH m.roles WHERE m.email = :email")
repository에 JOIN FETCH 쿼리 추가
-> 필요할 때만 명시적으로 함께 가져옴