EntityManager는 JPA(Java Persistence API)에서 엔티티를 관리하는 핵심 인터페이스입니다.
JPA를 통해 데이터베이스와 상호작용하며, 엔티티의 생명주기를 관리하고 쿼리를 실행하는 역할을 수행합니다.
엔티티 생명주기 관리
EntityManager는 엔티티를 영속성 컨텍스트(Persistence Context)에 등록하고 관리합니다.CRUD 작업
EntityManager는 엔티티를 데이터베이스에 저장, 조회, 수정, 삭제하는 메서드를 제공합니다.persist(entity): 엔티티를 영속성 컨텍스트에 등록.find(entityClass, id): 데이터베이스에서 엔티티를 조회.merge(entity): 준영속 상태의 엔티티를 다시 영속 상태로 병합.remove(entity): 엔티티를 삭제 예약 상태로 변경.JPQL 실행
TypedQuery<Member> query = em.createQuery("SELECT m FROM Member m WHERE m.name = :name", Member.class);
query.setParameter("name", "John");
List<Member> members = query.getResultList();
트랜잭션 관리
persist, merge, remove)은 반드시 트랜잭션 안에서 실행되어야 합니다.EntityTransaction을 통해 제어합니다.em.getTransaction().begin();
em.persist(entity);
em.getTransaction().commit();
캐싱
EntityManager는 영속성 컨텍스트에 이미 존재하는 엔티티를 재사용하여 불필요한 데이터베이스 조회를 줄입니다.| 메서드 | 설명 |
|---|---|
persist(Object entity) | 엔티티를 영속성 컨텍스트에 저장. |
find(Class<T> clazz, Object primaryKey) | 주어진 ID로 엔티티를 조회. |
merge(Object entity) | 준영속 상태의 엔티티를 다시 영속 상태로 병합. |
remove(Object entity) | 엔티티를 삭제 예약 상태로 변경. |
flush() | 영속성 컨텍스트의 변경 내용을 데이터베이스에 반영. |
clear() | 영속성 컨텍스트를 초기화. |
생성
EntityManager는 EntityManagerFactory를 통해 생성됩니다.EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistenceUnitName");
EntityManager em = emf.createEntityManager();
사용
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin(); // 트랜잭션 시작
Member member = new Member();
member.setName("John Doe");
em.persist(member); // 엔티티 저장
tx.commit(); // 트랜잭션 커밋
} catch (Exception e) {
tx.rollback(); // 에러 발생 시 롤백
} finally {
em.close(); // 엔티티 매니저 닫기
}
스레드 안전하지 않음
EntityManager는 스레드 안전하지 않으므로, 여러 스레드에서 공유하면 안 됩니다.EntityManager를 생성하거나, 스프링에서는 @Transactional을 통해 관리합니다.트랜잭션 범위 내 사용
close() 호출
close()를 호출하여 리소스를 해제해야 합니다.EntityManager는 JPA의 중심으로, 엔티티의 생명주기와 데이터베이스 작업을 관리하는 역할을 합니다.추가 학습 자료