🤔 영속성 컨텍스트는 일종의 JPA 컨테이너 안에서 동작하는 entity의 맥락을 관리하는 것이다. 이 안에서 entity는 생성되고 지워지고 조회된다. 그 context 안에서 가장 중요한 역활을 하는 것이 EntityManager 객체이다. 이 역활을 알아보고, EntityManager가 entity를 처리하는 과정에서 Cache를 사용하는데 어떻게 사용하는지 알아보자.
@SpringBootTest
public class EntityManagerTest {
@Autowired
private EntityManager entityManager;
@Test
void entityManagerTest() {
System.out.println(entityManager.createQuery("select u from User u").getResultList()); // entityManager에서 직접 쿼리를 만들서 사용
// userRepository.findAll(); 이거와 같다.
}
@Test
void cacheFindTest() {
System.out.println(userRepository.findByEmail("martin@fast.com"));
System.out.println(userRepository.findByEmail("martin@fast.com"));
System.out.println(userRepository.findByEmail("martin@fast.com"));
}
select
user0_.id as id1_7_,
user0_.created_at as created_2_7_,
user0_.updated_at as updated_3_7_,
user0_.email as email4_7_,
user0_.gender as gender5_7_,
user0_.name as name6_7_
from
user user0_
where
user0_.email=?
@SpringBootTest
@Transactional
public class EntityManagerTest {
@Test
void cacheFindTest() {
System.out.println(userRepository.findById(2L).get());
System.out.println(userRepository.findById(2L).get());
System.out.println(userRepository.findById(2L).get());
}
select
...
...
where
user0_.id=?
User(super=BaseEntity(createdAt=2022-02-11T16:44, updatedAt=2022-02-11T16:44), id=2, name=demis, email=demis@fast.com, gender=null)
User(super=BaseEntity(createdAt=2022-02-11T16:44, updatedAt=2022-02-11T16:44), id=2, name=demis, email=demis@fast.com, gender=null)
User(super=BaseEntity(createdAt=2022-02-11T16:44, updatedAt=2022-02-11T16:44), id=2, name=demis, email=demis@fast.com, gender=null)
@Test
void cacheFindTest() {
userRepository.deleteById(1L);
}
Hibernate:
select
...
...
from
user user0_
left outer join
user_history userhistor1_
on user0_.id=userhistor1_.user_id
where
user0_.id=?
Hibernate:
update
review
set
user_id=null
where
user_id=?
Hibernate:
delete
from
user
where
id=?
@Transactional
public class EntityManagerTest {
@Test
void cacheFindTest2() {
User user = userRepository.findById(1L).get();
user.setName("marrrrrrrtin");
userRepository.save(user);
System.out.println("---------------------");
user.setEmail("marrrrrrtin@fast.com");
userRepository.save(user);
}