본문 바로가기
JPA

[JPA] Persistence context(영속성 컨텍스트)와 EntityManager

by 곰민 2023. 1. 29.
728x90

JPA와 ORM에 대한 간략한 정의와 JPA에서 중요한 영속성 컨텍스트(Persistence Context)와 엔티티 매니저(Entity Manager), 영속성 컨텍스트 타입(Persistence Context type), 영속성 컨텍스트(Persistence Context)의 장점등에 대해서 알아보도록 하겠습니다.


JPA, ORM


JPA는 ORM(Object–relational mapping)이며 객체 지향과 Database간 발생하는 차이를 매핑해줍니다.

객체는 객체대로 설계하고 DB와의 차이점에 대해서는 ORM통해서 매핑하게됩니다.

SQL중심적 개발에서 객체 중심으로 개발할 수 있게 되며 데이터베이스에 종속적이지 않게 됩니다.

JPA는 JDBC API를 통해서 DB에 접근하며 java application과 JDBC API 사이에 존재하게 됩니다.

JPA는 인터페이스의 모음이며 HIbernates는 그 구현체입니다 (Hibernates를 제외하고도 , EclipseLink, DataNucleus존재)

 

Entity는 DB 테이블과 매핑되는 객체라고 생각하시면 됩니다.

 

자그러면 JPA에서 중요한 영속성 컨텍스트(Persistence context)와 EntityManager에 대해서 간략하게 알아보도록 하겠습니다

엔티티 매니저 팩터리와 엔티티 매니저(Entity Manager Factory & Entity Manager)


EntityManagerFactory

EntityManagerFactory는 Entity Manager를 만들고 구성하는법을 제공하는 interface입니다.
일반적으로 JPA의 구현체인 Hibernate나 EclipseLink에 의해서 생성되며 Entity Manager 인스턴스를 생성하는데 사용됩니다.

위 그림에서도 EntityManagerFactory를 활용하여 EntityManager1,2 인스턴스를 생성합니다.

 

EntityManager

EntityManager는 DB table과 mapping된 객체인 Entity에 대한 CRUD 작업을 수행하기 위한 method들을 제공하며
Entity의 라이프 사이클과 영속성 관리등을 담당합니다.

 

 

PersistenceContext(영속성 컨텍스트)는 무엇일까?


An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle are managed. The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities.

OracleDoc에서 설명하는 영속성 컨텍스트(PersistenceContext).

영속성 컨텍스트(Persistence Context)는 영속화 되어있는 entity identity에 대해 unique한 entity 인스턴스가 존재하는 entity 인스턴스의 집합이라고 되어있습니다.

 

영속성 컨텍스트(Persistence Context)는 즉
1. entity의 영속화에 관여하며

2. entity들이 DB로 바로 가지 않고 entity를 저장하는 환경으로서의 역활을 합니다.

 

영속성 컨텍스트는 논리적인 개념이며 아래 코드와 같이 EntityManger를 통해서 영속성 컨텍스트에 접근하게 됩니다.

 

EntityManager.persist(entity);

 

EntityManager.persist를 활용하여 해당 entity를 영속성 컨텍스트로 보내고
영속성 컨텍스트를 통해서 해당 데이터를 영속화 한다 라는 의미입니다.

 

J2EE 스프링 프레임워크 같은 컨테이너 환경내에서의 관계도

 

영속성 컨텍스트(PersistContext) Type은 무엇이 있을까요?


영속성 컨택스트는 두가지 타입을 허용합니다

 

1. Transaction-scope persistence context

2. Extended-scope persistence context

 

그 두가지에 대해서 알아봅시다.

 

 

출처:https://www.baeldung.com/jpa-hibernate-persistence-context

Transaction-scope persistence context는 transaction에 바이딩 됩니다.
transaction이 완료되는 즉시 영속성 컨텍스트에 있는 entity들은 영구 스토리지 즉 DB로 flush 됩니다.

transaction 내부에서 작업을 수행할 때 EntityManager는 영속성컨텍스트가 하나라도 존재한다면 존재하는 것을 사용하며
하나라도 없다면 영속성 컨텍스트를 생성합니다.

 

Default persistence context type은 TRANSACTION입니다.
EntityManager에게 영속성 컨텍스트를 사용하게 하기 위해 @PersistenceContext  어노테이션을 달아주면 됩니다.

@PersistenceContext
private EntityManager entityManager;

 

 

 

출처:https://www.baeldung.com/jpa-hibernate-persistence-context

Extended-scope persistence context는 영속성 컨텍스트가 multiple transaction에 걸쳐서 존재할 수 있습니다.

transaction 없이 entity를 영속성컨택스트에 유지 시킬수는 있지만 transaction없이 DB에 Flush 할 수는 없습니다.

 

EntityManagaer에 @PersistenceContext 어노테이션에
type값으로 PersistenceContextType.EXTENDED를 명시해야 합니다.

@PersistenceContext(type = PersistenceContextType.EXTENDED)
private EntityManager entityManager;

 

 

 

영속성 컨텍스트(persistence-context)의 장점


그렇다면 영속성 컨텍스트를 사용함으로써 얻을 수 있는 장점들은 어떤것이 존재할까요?
영속성 컨텍스트는 데이터베이스와 애플리케이션 중간에 위치하며 중간에 위치함으로서 그리고 영속성컨텍스트가 제공하는 기능등을 통해서 얻는 이점들이 존재합니다.

 

성능 향상

영속성 컨텍스트를 사용하면 엔티티를 메모리에 캐시함으로서
빈번하게 데이터베이스에 접근하는것을 줄일 수 있고, 데이터베이스 로드 또한 줄어듭니다.

 

간소화된 데이터베이스 엑세스

엔티티를 관리하기 위한 단순화된 API를 제공하여 데이터베이스 액세스를 단순화합니다.
이를 통해 개발자는 낮은 수준의 데이터베이스 엑세스를 위한 쿼리에 집중하기 보다는

애플리케이션의 비즈니스 로직에 집중할 수 있습니다.

 

데이터 일관성의 향상

영속성 컨텍스트는 엔티티 라이프사이클즉 엔티티의 상태에 대한 관리를 자동적으로 관리함으로서 엔티티가 일관성있도록 보장해줍니다.

 

향상된 scalability

영속성 컨텍스트는 데이터베이스에대한 접근과 엔티티의 상태관리를 자동적으로 하기 때문에 확장성에서도 이점을 갖습니다.

 

영속성 컨텍스트가 관리하는 엔티티의 생명주기와, 1차캐시, 변경감지(dirty-check)에 관해서는 추후 포스팅하도록 하겠습니다.

 

참조


OracleDoc

baldung

김영한 java 표준 orm jpa 강의

728x90

댓글