[에러일기/Spring] org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role:

사그미·2025년 9월 8일

에러일기

목록 보기
3/3
post-thumbnail

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. DB에서 Member 조회 (세션 O)→ roles는 아직 로드 안 됨
  2. 트랜잭션 끝 (세션 X)
  3. member.getRoles() 호출 → 세션이 없어서 실제 데이터 못 가져옴
  4. 에러 발생

해결방법

방법 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 쿼리 추가
-> 필요할 때만 명시적으로 함께 가져옴

profile
애면글면

0개의 댓글