221217 더티 체킹, Dirty Checking

Jongleee·2022년 12월 17일
0

TIL

목록 보기
132/576

더티 체킹, Dirty Checking

Transaction 안에서 엔티티의 변경이 일어나면, 변경 내용을 자동으로 데이터베이스에 반영

dirty - 변경된 부분을 의미

데이터베이스에 변경 데이터를 저장하는 시점

  1. Transaction Commit
  2. EntityManager Flush
  3. JPQL 사용

더티체킹의 대상

영속성 컨택스트(Persistence Context) 안에 있는 엔티티

더티 체킹의 조건

  1. Service Layer에서 @Transactional을 사용하는 경우

    @Service
    public class ExampleService {
         @Transactional
         public void updateInfo(Long id, String name) {
              User user = userRepository.findById(id);
              user.setName(name);
         }
    }
  2. EntityTransaction을 이용해서 트랜잭션을 범위를 지정하고 사용하는 경우

    @Service
    public class ExampleService {
         public void updateInfo(Long id, String name) {
              EntityManager em = entityManagerFactory.createEntityManager();
              EntityTransaction tx = em.getTransaction();
              // 1. 트랜잭션 시작
              tx.begin();
              // 2.User 엔티티를 조회 & User 스냅샷 생성
              User user = em.find(User.class, id);
              // 3.User 엔티티의 name을 변경
              user.setName(name);
              // 4. 트랜잭션
              // 5.User 스냅샷과 최종 user의 내용을 비교해서 Dirty를 Checking 해서 Update Query 발생
              tx.commit();
         }
    }

위 1번/2번에서 더티 체킹이 일어나면 user의 업데이트에 대한 메서드를 호출하지 않았음에도 불구하고 Query가 발생

트랜잭션 커밋 이후, 트랜잭션이 끝나는 시점에 모든 엔티티에 대한 정보를 DB에 반영

출처:https://interconnection.tistory.com/121

0개의 댓글