본문 바로가기

Spring/JPA

JPA- flush와 영속성 관리

flush

 플러쉬를 사용하면 쓰기지연 저장소에 있는 쿼리를 DB에 날릴 수 있다.

쉽게 말하면 영속성 컨텍스트의 변경 내용을 DB에 반영하는 것이다.

em.flush();  //em.commit() 이전에 플러시해줌

commit을 하면 자동을 flush가 되지만 em.flush()로 commit 이전에 flush를 진행할 수도 있다.

준영속 상태

 

1) em.detach(entity);

특정 엔티티만 영속성 컨텍스트에서 제거

package hellojpa;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class JpaMain {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();

        try{
            Member member = em.find(Member.class, 150L);//영속성 컨텍스트에 저장
            member.setName("aaaaa"); //update 쿼리를 쓰기지연 저장소에 올림

            em.detach(member); //준영속 상태(쿼리 못날림)

            tx.commit();
        } catch(Exception e) {
            tx.rollback(); //오류 발생 시 롤백
        } finally {
            //종료
            em.close();
        }
        emf.close();
    }
}

Hibernate: 
    select
        member0_.id as id1_0_0_,
        member0_.name as name2_0_0_ 
    from
        Member member0_ 
    where
        member0_.id=?

 member는 setName()을 통해서 이름이 변경되므로 영속성 컨텍스트에서 member의 이름이 변경된다. 그 후 detach를 하여 영속성 컨텍스트에서 member를 제거하였다. 따라서 비록 member의 이름은 변경이 되었다고 하지만 더 이상 영속성 컨텍스트에 있지 않으므로 DB에 업데이트 쿼리가 날라가지 않는다.

 따라서 출력을 보면 select문만 보이고 update문은 보이지 않는다.

 

2) em.clear();

영속성 컨텍스트를 비움

 

3) em.close();

영속성 컨텍스트를 종료함

'Spring > JPA' 카테고리의 다른 글

JPA- 연관관계 매핑  (0) 2023.03.05
JPA- 중요! 엔티티 매핑  (0) 2023.02.28
JPA- 영속성 컨텍스트  (0) 2023.02.28
JPA- EntityManager.find()로 조회하기  (0) 2023.02.16
JPA- 관련 개념 정리  (0) 2023.02.16