Files
llm-wiki/raw/official-docs/transaction-template-spring-official.md

106 lines
9.4 KiB
Markdown

---
title: "Programmatic Transaction Management :: Spring Framework Reference"
source_type: official-doc
url: https://docs.spring.io/spring-framework/reference/data-access/transaction/programmatic.html
archive_url:
status: raw
confidence: high
tags: [ca-transaction-boundary, transaction-template, spring-official, programmatic-tx, transaction-management]
related_projects: [ca-skeleton-operational-contract]
related_branches: [feature-application-port-usecase-contract, feature-transaction-concurrency-contract]
created: 2026-05-22
last_reviewed: 2026-05-27
---
# Programmatic Transaction Management :: Spring Framework Reference
> Layer: `raw/official-docs/` — Spring Framework 7.x reference, `data-access/transaction/programmatic` 섹션 verbatim 발췌.
> ca-tmpl TransactionPort adapter 의 내부 구현 후보 (`TransactionTemplate.execute(...)`) 의 1차 근거.
## Parent / 활용 branch (필수)
| Branch | 이 자료가 정당화하는 결정 |
|---|---|
| [[raw/branch-notes/feature-application-port-usecase-contract]] | TransactionPort adapter 가 내부적으로 `TransactionTemplate` 을 사용하는 구현 선택의 공식 근거 (Spring 권장 programmatic 패턴) |
| [[raw/branch-notes/feature-transaction-concurrency-contract]] | Topic 2 — Transaction Boundary 대안 2 (TransactionTemplate programmatic) 의 공식 정의·콜백 시맨틱·imperative vs reactive 권장 비교 baseline |
## 컨텍스트
ca-tmpl 의 TransactionPort 결정에 대한 대안 2: **`TransactionTemplate` 명시적 호출**. Spring 이 공식적으로 권장하는 programmatic 패턴이며, port adapter 내부 구현으로 종종 채택됨.
## 출처 / Source
- 원본 URL: https://docs.spring.io/spring-framework/reference/data-access/transaction/programmatic.html
- 아카이브 URL: (미수집)
- 저자 / 조직: Spring Framework / VMware (Broadcom)
- 발행일: Spring Framework 7.x reference (current, rolling docs)
- 마지막 확인일: 2026-05-27
## 핵심 인용 / Key quotes (verbatim)
> [§Using the TransactionTemplate] "The `TransactionTemplate` adopts the same approach as other Spring templates, such as the `JdbcTemplate`. It uses a callback approach (to free application code from having to do the boilerplate acquisition and release transactional resources) and results in code that is intention driven, in that your code focuses solely on what you want to do."
> [§Programmatic Transaction Management] "The Spring team generally recommends the `TransactionTemplate` for programmatic transaction management in imperative flows and `TransactionalOperator` for reactive code."
> [§Using the TransactionTemplate] "Application code that must run in a transactional context and that explicitly uses the `TransactionTemplate` resembles the next example. You, as an application developer, can write a `TransactionCallback` implementation (typically expressed as an anonymous inner class) that contains the code that you need to run in the context of a transaction. You can then pass an instance of your custom `TransactionCallback` to the `execute(..)` method exposed on the `TransactionTemplate`."
> [§Using the TransactionTemplate] "Code within the callback can roll the transaction back by calling the `setRollbackOnly()` method on the supplied `TransactionStatus` object, as follows:"
```java
return transactionTemplate.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
updateOperation1();
return resultOfUpdateOperation2();
}
});
```
## Claims Extracted / 추출된 주장
| Claim ID | Claim (이 자료가 직접 말하는 것) | Evidence quote | Strength | Applies to | Does not prove |
|---|---|---|---|---|---|
| TX-TMPL-C1 | `TransactionTemplate``JdbcTemplate` 등 다른 Spring template 와 동일한 **callback 접근법** — 트랜잭션 리소스 획득/해제 boilerplate 를 application code 에서 제거하여 intention-driven 코드를 가능하게 함 | [§Using the TransactionTemplate] "The `TransactionTemplate` adopts the same approach as other Spring templates... It uses a callback approach (to free application code from having to do the boilerplate acquisition and release transactional resources) and results in code that is intention driven..." | `official-vendor-doc` | Spring `TransactionTemplate` 사용 시 | callback 접근법이 declarative `@Transactional` 보다 더 권장된다는 뜻은 아님 — 둘 다 공식 옵션 |
| TX-TMPL-C2 | Spring 팀의 **programmatic transaction management 공식 권장**: imperative flow 에는 `TransactionTemplate`, reactive code 에는 `TransactionalOperator` | [§Programmatic Transaction Management] "The Spring team generally recommends the `TransactionTemplate` for programmatic transaction management in imperative flows and `TransactionalOperator` for reactive code." | `official-vendor-doc` | programmatic transaction management 가 필요한 경우 | programmatic 이 declarative 보다 우월하다는 뜻은 아님 — 두 패러다임의 권장 도구 선택만 명시 |
| TX-TMPL-C3 | 사용 패턴: 개발자가 **`TransactionCallback` 구현** (보통 anonymous inner class) 을 작성하고, `TransactionTemplate.execute(..)` 메서드에 전달 | [§Using the TransactionTemplate] "...you can write a `TransactionCallback` implementation (typically expressed as an anonymous inner class) that contains the code that you need to run in the context of a transaction. You can then pass an instance of your custom `TransactionCallback` to the `execute(..)` method..." | `official-vendor-doc` | `TransactionTemplate.execute()` 호출 시 | Java 8+ lambda 가 동일하게 동작한다는 뜻을 본 인용으로 직접 보장할 수는 없음 (별도 확인 필요 — 실무에선 가능) |
| TX-TMPL-C4 | callback 내부에서 `TransactionStatus.setRollbackOnly()` 호출로 **명시적 rollback** 가능 | [§Using the TransactionTemplate] "Code within the callback can roll the transaction back by calling the `setRollbackOnly()` method on the supplied `TransactionStatus` object..." | `official-vendor-doc` | `TransactionTemplate.execute()` 콜백 내부 | exception throwing 으로도 rollback 가능한지는 본 인용 범위 밖 (RuntimeException 으로 rollback 되는 declarative 시맨틱과의 매핑은 별도) |
## Usage Boundaries / 적용 경계
- **이 자료가 직접 증명하는 것**:
- `TX-TMPL-C1` ~ `C4`: Spring 공식의 `TransactionTemplate` callback 패턴, imperative/reactive 권장 도구 분리, 사용 시그니처, 명시적 rollback 메커니즘
- **이 자료가 증명하지 않는 것**:
- `TransactionTemplate` 을 application service 에서 직접 사용하는 것이 clean architecture 와 양립 가능하다는 평가 (여전히 `org.springframework.transaction.support.TransactionTemplate` import 발생 — architecture-level 판단은 ca-tmpl 측 결정)
- `TransactionTemplate``@Transactional` 보다 성능상 우월/열등하다는 비교 (본 페이지는 성능 비교 미포함)
- exception throwing 시 자동 rollback 시맨틱 (`RuntimeException` 의 기본 rollback rule 등 — 별도 페이지)
- **내 프로젝트에 적용하려면 추가 확인이 필요한 것**:
- ca-tmpl 의 TransactionPort adapter 가 `TransactionTemplate.execute()` 를 호출할 때 lambda 사용 가능 여부 (실무 통례지만 본 인용은 anonymous inner class 만 예시)
- `setRollbackOnly()` 와 exception 기반 rollback 의 우선순위 / 충돌 처리
## 메모 / Notes (내 프로젝트 해석)
> 본 섹션은 자료 직접 인용 아님. ca-tmpl 결정 컨텍스트 해석.
- 적용 시나리오: 메서드 단위가 아니라 메서드 내부 일부 블록만 트랜잭션으로 묶고 싶을 때. 또는 reactive 가 아니지만 declarative AOP 를 피하고 싶을 때.
- 장점:
- 트랜잭션 경계가 코드에 명시적으로 보임. AOP proxy 우회 / self-invocation 같은 함정 없음.
- 한 메서드 안에서 트랜잭션 블록과 비트랜잭션 블록을 자유롭게 섞을 수 있음.
- reactive: `TransactionalOperator` 사용 (TX-TMPL-C2).
- 단점:
- application service 가 직접 사용하면 여전히 `org.springframework.transaction.support.TransactionTemplate` import 발생 → clean architecture 위반은 동일.
- 모든 트랜잭션 블록마다 callback boilerplate 발생.
- ca-tmpl (TransactionPort) 와의 차이: `TransactionTemplate`**구현 디테일**이고, ca-tmpl 은 그것을 한 단계 더 감싼 **port** 를 둠. 즉 TransactionPort 의 adapter 가 내부적으로 `TransactionTemplate.execute(...)` 를 호출하는 형태가 자연스러움.
- testability 영향: 중간 — port 없이 직접 쓰면 여전히 Spring 의존 테스트 필요. port 로 감싸면 ↑.
- code 복잡도 영향: 중간 — 콜백 noise.
## Related / 관련
- 같은 주제 다른 official-doc:
- [[raw/official-docs/at-transactional-spring-official]] (대안 1: declarative `@Transactional`)
- 적용 ca-tmpl branch-note:
- [[raw/branch-notes/feature-application-port-usecase-contract]]
- [[raw/branch-notes/feature-transaction-concurrency-contract]]
- canonical contract 섹션:
- [[raw/project-notes/ca-skeleton-operational-contract]] (§14. Transaction / Concurrency Contract, §5. Exception Ownership Contract)
- 대안 그룹: **Topic 2 — Transaction Boundary** (5종: TransactionPort / @Transactional direct / TransactionTemplate / Functional monad / Custom AOP) — 본 source 는 **대안 2**.
- 인용한 wiki 요약: (미작성)