-
[JPA] bulk data batch 작업 시 유의점개발 2022. 1. 6. 15:58
JPA 벌크 데이터 작업 시 유의점
JPA 의 벌크성 작업은 영속성 컨텍스트와 무관하다.
기존 엔티티 수정 메커니즘
JPA 는 엔티티를 영속성 컨텍스트에 보관한 후, DB에 반영한다.
이 때 최초상태를 복사해서 저장해두고, 플러시 시점에서 스냅샷과 엔티티를 비교하여 변경사항만을 DB 에 반영한다.기존 엔티티 수정 메커니즘은 다음과 같다.
- 트랜잭션을 커밋하기 전, 엔티티 매니저 내부에서
flush()
를 먼저 호출한다. - 엔티티와 스냅샷을 비교해서 변경 지점을 찾는다.
- 변경사항이 있는 경우 쓰기지연 SQL 저장소에 SQL 문을 생성해서 저장해 둔다.
- DB에 비로소 commit 될 때, SQL Query 를 DB로 보내서 실제로 반영한다.
벌크 수정 메커니즘
그러나 벌크 작업은 앞서 설명했던 것처럼 영속성 컨텍스트를 통하는 모든 작업을 생략한다.
그리고 DB에 직접 쿼리를 날린다.그런데 JPA 를 통해 엔티티를 조회 시 반드시 1차 캐시를 먼저 본다.
예를 들어
findById()
로 특정 엔티티를 찾을 때, 먼저 1차 캐시를 뒤져서 엔티티가 있는지 확인한 후 있으면 리턴한다.
그런데 만약에 배치작업을 통해서 Update 를 날린다면 1차 캐시는 업데이트 하지 않기 때문에
실제로 DB에 변경사항이 반영 되더라도 1차 캐시에는 이전 버전의 엔티티가 저장되어 있다.따라서 DB를 봤을 때는 제대로 됐는데 JPA 로 조회하니 데이터 업데이트가 안된 것처럼 보이는 것이다.
결론
배치작업을 통해 DB를 업데이트 했다면 영속성 컨텍스트를 초기화 해주자.
'개발' 카테고리의 다른 글
[Spring Boot] Field Injection 을 추천하지 않는 이유 (0) 2022.11.22 [DB] DB 조인 방식 3가지 (0) 2022.01.23 [CI] Jenkins 와 Github Webhook 으로 PR 유효성 체크하기 (0) 2021.12.29 [JPA] Primary Key가 아닌 필드를 참조하는 Foreign Key 를 만들때 (0) 2021.12.12 [TDD] TDD 로 알고리즘 문제 풀어보기 - 프로그래머스 42626, 더 맵게 (2) 2021.10.31 - 트랜잭션을 커밋하기 전, 엔티티 매니저 내부에서