| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 | 30 |
- Spring Security
- JPA
- psycopg2
- postgres
- sftp
- hadoop #hdfs
- spring
- Maven
- LazyInitializationException
- mysql
- AuthenticationPrincipal
- spring boot
- JSON Web Token
- Geoserver
- Docker
- 1093
- python
- insert into
- posgis
- Kafka
- Java
- Failed to load ApplicationContext
- nginx
- QGIS
- Linux
- #mojo
- RDB
- postgresql
- JWT
- uuid
- Today
- Total
FOREST_CHOI's BLOG
LazyInitializationException 예외 (feat.@AuthenticationPrincipal) 본문
LazyInitializationException 예외 (feat.@AuthenticationPrincipal)
Forest_Choi 2022. 7. 18. 16:18토이프로젝트로 개발을 진행하던 도중 LazyInitializationException 예외가 발생하였다.
다른 기술블로그들을 참고하였지만, 나의 근본적인 문제와 다른 문제였고 해결방법이 '이렇게 해도 되나?' 싶은게 대분이였다.
현재 내 프로젝트에서의 문제점은 이러했다.
1. @AuthenticationPrincipal을 편하게 받아오기위해 @CurrentMember(@CurrentUser라고많이씀) 을 설정하여 편하게 유저정보를 가져오게 하였음
2. 게시글 작성시 현재맴버를 가지고 오고 활용하는 과정에서 LazyInitializationException가 발생하였음
일단 LazyInitializationException 이란 무엇일까?
- 영속성 컨텍스트가 종료된 상황에서 LAZY LOADING된 proxy 객체에게 연관 Entity를 조회하라고 요청할 때 문제가 되어 발생하는 Exception이다.
- 나의 상황에서는 @CurrentMember 어노테이션을 통해 현재 로그인 한 유저정보를 Entity생명주기를 파악하지 못하여 발생한 문제였다.
해결방안으로는
1) CurrentMember를 통해 불러온 객체로 Entity를 다시 불러오기
2) Entity를 강제로 초기화하기
3) FetchType.EAGER
이렇게 세 가지가 대표적이였다.
첫 번째의 경우 문제는 해결이 가능하나, 찾아온 객체를 다시 조회하는 형태의 코딩은 부자연스럽다는 단점이 있었고,
세 번째의 경우에는 사용하지 않는 엔티티가 로딩되는 N+1의 문제가 발생할 수 있다는 것이였다.
(2번째는 잘 모르겠다...)
결국 궁극적으로 해결한 방법은 기존에 설정되어있는 OpenEntityManagerInterceptor의 우선순위를 높이는 방법이었다.
Spring boot는 기본적으로 Filter기반으로 동작하고 있기 때문에 Interceptor가 아니라 Filter로 교체해야했고, OpenEntityManaberInView 클래스를 따로 Bean으로 등록하면 해결된다는 것이였다.
(자세한 설명은 아래 참고한 블로그에서 확인하길 바람)
@Component
@Configuration
public class OpenEntityManagerConfig {
@Bean
public FilterRegistrationBean<OpenEntityManagerInViewFilter> openEntityManagerInViewFilter() {
FilterRegistrationBean<OpenEntityManagerInViewFilter> filterFilterRegistrationBean = new FilterRegistrationBean<>();
filterFilterRegistrationBean.setFilter(new OpenEntityManagerInViewFilter());
filterFilterRegistrationBean.setOrder(Integer.MIN_VALUE); // 예시를 위해 최우선 순위로 Filter 등록
return filterFilterRegistrationBean;
}
}
아래 두 블로그는 내가 이 문제를 해결하기 위해 참고한 블로그이다.
https://tecoble.techcourse.co.kr/post/2020-08-31-entity-lifecycle-1/
https://tecoble.techcourse.co.kr/post/2020-09-20-entity-lifecycle-2/
'프로그래밍 > JPA' 카테고리의 다른 글
| @Embedded, @Embeddable (0) | 2022.10.20 |
|---|---|
| JPA? (0) | 2022.10.16 |
| data.sql / insert 구문 시 pk 안들어가는 문제 (0) | 2022.09.23 |
| org.h2.jdbc.JdbcSQLDataException: Hexadecimal string contains non-hex character (0) | 2022.09.20 |
| 영속성 전이 - 삭제 (0) | 2022.08.01 |