[Spring Boot] JPA 강의 정리-7 (JPA 내부 구조-준영속)

Posted by 김성철

SpringBoot - JPA 강의 정리-7(JPA 내부 구조 - 준영속)

Entity의 생명주기

- 비영속 (new / transient)  
	영속성 컨텍스트와 전혀 관계가 없는 새로운 상태  
  
- 영속 (managed)  
	영속성 컨텍스트에 관리되는 상태  
  
- 준영속 (detached)  
	영속성 컨텍스트에 저장되었다가 분리된 상태  
  
- 삭제 (removed)  
	삭제된 상태  

준영속 상태

영속 -> 준영속  
영속 상태의 엔티티가 영속성 컨텍스트에서 분리(detached)  
영속성 컨텍스트가 제공하는 기능을 사용 못함  
  
1차 캐시에 올라간 상태는 영속 상태임  

준영속 상태로 만드는 방법

em.detach(entity)  
	특정 엔티티만 준영속 상태로 전환  
	=====================================================================  
	Member member = em.find(Member.class,100L);  
	member.setName("zzaazzaa");  
  
	//JPA에서 관리하지 않음  
	//영속성 컨텍스트에서제외댐  
	em.detach(member);  
  
	System.out.println("#### commit start ###");  
	tx.commit();//commit 하는 시점에 쓰기 지연 SQL 저장소에 있는  INSERT 쿼리가 실행됨  
	=====================================================================  
  
	결과 - update 쿼리문이 실행되지 않음, 원래는 commit 시점에서 update 쿼리가 실행됨  
	=====================================================================  
	Hibernate:  
		select  
			member0_.id as id1_0_0_,  
			member0_.name as name2_0_0_  
		from  
			MEMBER member0_  
		where  
			member0_.id=?  
	=====================================================================  
  
em.clear()  
	영속성 컨텍스트를 완전히 초기화  
	clear 후 같은 값을 조회하면 SQL이 다시 실행됨  
	=====================================================================  
	//영속성 컨텍스트 초기화  
	em.clear();  
	=====================================================================  
  
em.close()  
	영속성 컨텍스트를 종료  
	=====================================================================  
	//영속성 컨텍스트 종료  
	em.close();  
	//조회가 안됨 Session/EntityManager is closed  
	Member member1 = em.find(Member.class,100L);  
	=====================================================================