minlog
article thumbnail

 

1. 영속성 컨텍스트

> Entity 객체를 특별하게 감시하고 관리해주는 컨테이너

  • 영속성 컨텐스트란 엔티티를 영구 저장하는 환경이라는 뜻이다.
  • 애플리케이션과 데이터베이스 사이에서 객체를 보관하는 가상의 데이터베이스 같은 역할을 한다.
  • 엔티티 매니저를 통해 엔티티를 저장하거나 조회하면 엔티티 매니저는 영속성 컨텍스트에 엔티티를 보관하고 관리한다.

 

영속성 캐쉬가 flash가 되서 DB에 반영 되는 시점

  1. flash() 메서드를 명시적으로 호출하는 시점
  2. 트랜직션이 끝나서 해당 쿼리가 커밋되는 시점
  3. 복잡한 조회 조건의 jpk가 실행되는 시점

 

 

2. Entity 생명 주기 

'Entity' 하나의 객체에는 4가지의 상태가 존재한다. 

비영속상태(new/transient) , 영속상태 (managed), 준영속상태(detached),삭제상태(removed)

 

 

1 ) 비영속 상태(new/transient)

 

영속성 컨텍스트가 해당 Entity객체를 관리하지 않는 상태  (ex : @Transient)

이때는 자바 오브젝트로 취급된다.

@Transactional
public void put(){
    User user = new User();
    user.setName("ji");
    user.setEmail("ji@naver.com");
}

 

 

2 ) 영속 상태 (managed) 

Entity가 영속성 컨텍스트에서 관리되는 상태이다.

객체의 변화를 별도로 처리하지 않더라도 DB에 수정의 내용을 반영시켜준다. 이것을 영속성 컨텍스트가 제공해주는 더티(변경)체크라고한다. ( Entity객체를 처음 컨텍스트가 로딩을 할때 스냅샷으로 복사해서 가지고 있다가 변경내용을 DB 에 저장해야하는 시점에 스냅샷과 현제 ENtity객체의 상태를 비교하여  저장 코드가 없다고 하더라도 DB에 반영해준다. )

주의할 점은 대량의 Entity를 가지고 있을경우 로직의 성능저하가 발생하기도 한다.

@Autowired
private EntityManager entityManager;
@Autowired
private UserRepository userRepository; 

@Transactional
public void put(){
    User user = new User();
    user.setName("ji");
    user.setEmail("ji@naver.com");

//1. save() 저장 실행 시 영속화 효과가 있다.
    userRepository.save(user);

//2. entityManager를 사용하여 영속화 하여 관리하는 상태가 된다.
    entityManager.persist(user);
    // save메서드를 재 사용하지 않아도 변경시 디비에 바로 업데이트가 진행된다.
    user.setName("newJi"); 
}

 

 

 

2 ) 준영속 상태(detached)

영속화 상태였던 객체를 분리해서 영속성 컨텍스트 밖으로 꺼내는 동작이다.

(detached 외에도 clear가 있으나 두개의 속성은 다르다)

@Autowired
private EntityManager entityManager;
@Autowired
private UserRepository userRepository; 

@Transactional
public void put(){
    User user = new User();
    user.setName("ji");
    user.setEmail("ji@naver.com");

    entityManager.persist(user);
    entityManager.detach(user);
    //detach 후에 적용한 setName 메서드는 저장되지 않는다.
    user.setName("newJi"); 
    
    //merge를 실행시 데이터가 반영된다.
    entityManager.merge(user);
    //clear 실행시 변경을 요청했던 작업도 제거된다.
    entityManager.clear(user);
    
}

 

 

4 ) 삭제상태(removed)

실제 DB를 삭제 요청한 상태이다.

@Autowired
private EntityManager entityManager;
@Autowired
private UserRepository userRepository; 

@Transactional
public void put(){
    User user = new User();
    user.setName("ji");
    user.setEmail("ji@naver.com");
	entityManager.persist(user);
    
    User user1 = userRepository.findById(1L).get();
	entityManager.remove(user1);
}

 

profile

minlog

@jimin-log

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!