> For the complete documentation index, see [llms.txt](https://leehyokyun.gitbook.io/openbook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://leehyokyun.gitbook.io/openbook/2-5.-spring-core-4-entity-manager-transaction-manager.md).

# 2-5. Spring Core #4 : Entity Manager / Transaction Manager

Spring framework의 core - Entity Manager / Transaction Manager에 대하여

### 1. Transaction Manager와 Entity Manager의 정의 및 상호 작용을 통한 원자성 구현

* Entity Manager의 역할: JPA(ORM) 기반 영속성 컨텍스트의 실질적인 연산 작업을 수행하기 위한 객체다. 데이터베이스의 스냅샷을 자바 객체화하여 영속 상태를 유지하며, `entityManager.persist(member)`를 통한 저장, `entityManager.find(Member.class, 1L)`을 통한 조회, `entityManager.remove(member)`를 통한 삭제 등 실제 구체적인 DB 연산 처리를 직접 담당한다.
* Transaction Manager의 역할: 트랜잭션의 시작, 커밋(Commit), 롤백(Rollback) 등 전체적인 트랜잭션 생명 주기를 철저하게 관리하는 주체다. 내부적으로 연산 적용을 위한 Entity Manager를 총괄 관리하고 제어한다.
* 상호 작용과 원자성 보장: Entity Manager가 실제 데이터베이스 레이어의 실무 작업을 유기적으로 수행하면, Transaction Manager는 그 분산된 작업들을 "하나의 원자적 작업(All or Nothing)"으로 단단히 묶어 전체 비즈니스 흐름의 트랜잭션 원자성을 완벽하게 달성한다.

### 2. Spring 트랜잭션 인프라를 구성하는 3대 Transaction Manager의 핵심 매커니즘

* JdbcTransactionManager: 과거 DataSourceTransactionManager의 역할을 포괄하며, RedisTemplate이나 일반 JDBC 및 MyBatis 구동 환경처럼 JDBC 기반의 Connection 취득 및 커밋/롤백 연산을 직접적으로 수행한다.
* JpaTransactionManager: JPA 기술 표준에 특화된 매니저다. 영속성 컨텍스트 기반의 변경 감지(Dirty Checking), 영속성 컨텍스트 관리자 제어, DB Flush 유도 등 JPA 고유의 영속성 메커니즘을 전담하여 처리하고 최종 트랜잭션 흐름을 반영하거나 롤백한다.
* TransactionSynchronizationManager: 스프링 프레임워크 내부에서 ThreadLocal 인프라를 기반으로 현재 실행 스레드에 트랜잭션 흐름(Connection)을 결합하여 동기화하고 관리하는 핵심 자원 관리자다. 이를 통해 동일한 트랜잭션 바운더리 안에서는 몇 번을 호출하더라도 매번 새로운 커넥션을 맺지 않고 동일한 Connection 자원을 안전하게 공유하고 재사용할 수 있도록 일관성을 보장한다.

### 3. @Transactional의 ThreadLocal 기반 작동 원리와 @Async 결합 시의 구조적 예외 현상

* ThreadLocal 기반의 동기화 원리: `@Transactional` 애노테이션은 기본적으로 자바의 `ThreadLocal` 저장소를 활용하여 구동 스레드 내에 트랜잭션 흐름과 물리적 커넥션을 격리 저장한다. 이 메커니즘을 통해 하나의 스레드 선상에서 원자성을 확보하게 된다.
* @Async 결합 시의 스레드 분리 현상
  * ```
    @Transactional public void a() { asyncMethod(); }
    ```
  * ```
    @Async public void asyncMethod() { ... }
    ```
* 위 호출 구조와 같이 `@Transactional`이 선언된 메서드 a() 내부에서 비동기 실행을 유도하는 `@Async` 메서드를 호출하게 되면, 프레임워크는 완전히 새로운 별도의 스레드(Thread)를 동적으로 할당하여 `asyncMethod()`를 실행한다.
* 트랜잭션 전파 불가 및 커넥션 공유 단절: 자바의 ThreadLocal 자원은 다른 스레드 간에 원천적으로 공유되거나 전파될 수 없다. 따라서 메인 스레드인 a()에서 실행 중이던 트랜잭션 상태와 데이터베이스 커넥션 자원은 새로운 스레드로 절대 전파되지 않으며, 두 메서드 간의 물리적인 커넥션 공유는 완벽하게 차단된다. 비동기 스레드는 자신만의 독립적인 커넥션을 새로 취득하여 별개의 트랜잭션 런타임을 형성하게 된다.
* 따라서 @TransactionalEventListener(phase=AFTER\_COMMIT)과 같은 Thread 기반의 트랜잭션 컨텍스트 결합이 필요한 것이다.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://leehyokyun.gitbook.io/openbook/2-5.-spring-core-4-entity-manager-transaction-manager.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
