숑숑이의 개발일기

EntityManagerFactory란?

EntityManagerFactory는 EntityManager를 생성하는 인터페이스다. 최초 생성 시 커넥션풀 생성을 포함한 여러 작업들을 수행하여 생성비용이 비싸다. 일반적으로 애플리케이션에서 생성 후 하나의 인스턴스를 공유하도록 설계되어있다. 여러 스레드가 동시에 접근해도 안전하다.

 

META-INF/persistence.xml에 설정한 정보를 기반으로 엔티티 매니저 팩토리를 생성한다. 아래와 같은 코드로 생성할 수 있다.

EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");

 

 

Spring Boot에서는 JPA 사용 시 application.properties 또는 application.yml 파일에서 설정한다.

spring.datasource.hikari.jdbc-url=jdbc:mysql://localhost/test
spring.datasource.hikari.username=user
spring.datasource.hikari.password=1234!

 

EntityManager란?

엔티티를 저장/수정/삭제/조회 등 엔티티와 관련된 모든 일을 처리할 때 직접적으로 사용되는 인터페이스다. 

엔티티 매니저는 쉽게말해 엔티티를 저장하는 가상의 DB이다. 엔티티매니저는 내부에 데이터베이스 커넥션을 유지하며 데이터베이스와 통신한다. (보통 트랜잭션을 시작할 때 커넥션을 얻는다)

  • 트랜잭션 내에서 엔티티를 영속화하고 업데이트
  • 엔티티의 상태를 추적, 관리하므로 엔티티를 영속화할 때 자동으로 데이터베이스에 쿼리를 실행한다.

 

EntityManager는 EntityManagerFactory를 통해 아래와 같이 생성한다.

EntityManager em = emf.createEntityManager();

엔티티 매니저는 여러 스레드가 접근하면 동시성 문제가 발생하므로 스레드 간에 절대 공유하면 안된다.

 

 

EntityManager가 제공하는 주요 메서드 (엔티티)

메서드 설명
persist(Object entity) 엔티티를 영속화(저장)
merge(Object entity) 엔티티를 병합(준영속 상태의 엔티티를 영속 상태로 만들거나, 영속 상태의 엔티티를 업데이트할 때 사용)
remove(Object entity) 엔티티를 삭제
find(Class<T> entityClass, Object primaryKey) 엔티티를 조회
getReference(Class<T> entityClass, Object primaryKey) 엔티티의 참조를 조회

 

 

https://do-study.tistory.com/61
https://bnzn2426.tistory.com/m/143

 

profile

숑숑이의 개발일기

@숑숑-

풀스택 개발자 준비중입니다