could not initialize proxy [ ... ] - no Session(JPA)
org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: could not initialize proxy [kr.co. ... ] - no Session
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy [kr.co. ... ] - no Session
[http-nio-8081-exec-3] WARN o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: could not initialize proxy [kr.co. ... ] - no Session]
해당 에러는 JPA를 사용해 데이터를 select할 때 발생할 수 있는 에러로
1:N의 관계를 가지고 있는 변수에 설정한 LAZY Loading 때문에 발생한다.
@ManyToOne(fetch = FetchType.LAZY)
// application.yml
jpa:
database: MYSQL
show-sql:
properties:
open-in-view: false
Open Session In View를 true로 설정하지 않으면 트랜잭션 시작 시점에 영속성 컨텐스트가 시작되어 트랜잭션이 종료되는 시점에 영속성 컨텍스트가 소멸되게 된다.
영속성 컨텐스트가 없어졌기 때문에 컨트롤러에서 가져올 때 조회할 수 없는 것이다.
해결 방법
1. Service.java 파일에서 DTO로 변환 후에 Controller로 리턴한다.
new ObjectDTO(ObjectEntity);
2. 변수의 설정을 즉시 로딩(Earger)으로 변경한다.
@ManyToOne(fetch = FetchType.EAGER)
그러나 즉시 로딩을 사용하는 경우 JPQL을 사용하면 N+1 문제가 발생할 수 있기 때문에 권장하지 않는다.
출처
https://jwdeveloper.tistory.com/310
(JPA) could not initialize proxy - no Session (1)
JPA를 사용하다 보면 아래 오류를 빈번하게 마주치게 된다. could not initialize proxy - no Session 해당 오류의 원인을 Open Session In View와 관련지어 정리해보고자 한다. 또한 영속성 컨텍스트의 시작과
jwdeveloper.tistory.com
https://cantcoding.tistory.com/78
JPA/ could not initialize proxy - no Session
1.문제점 JPA를 통한 개발을 하다보면 한번쯤 만날 수 밖에없는 에러이다. JPA를 사용하여 DB에 저장된 리소스를 불러와서 반환하는 경우, 혹은 사용할 때 발생했던 에러이다. 2.접근 JPA에 대한 이
cantcoding.tistory.com