Spring Framework's comprehensive transaction management APIs and support classes for imperative and reactive applications
npx @tessl/cli install tessl/maven-org-springframework--spring-tx@6.2.00
# Spring TX
1
2
Spring TX provides comprehensive transaction management capabilities for Spring applications, offering a vendor-neutral programming model that abstracts over various transaction management systems including JTA, JDBC, Hibernate, and reactive transactions. It enables both declarative and programmatic transaction management with support for various propagation behaviors, isolation levels, and rollback rules.
3
4
## Package Information
5
6
- **Package Name**: org.springframework:spring-tx
7
- **Package Type**: maven
8
- **Language**: Java (with Kotlin support)
9
- **Installation**: `implementation 'org.springframework:spring-tx:6.2.8'` (Gradle) or `<dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>6.2.8</version></dependency>` (Maven)
10
11
## Core Imports
12
13
```java
14
import org.springframework.transaction.PlatformTransactionManager;
15
import org.springframework.transaction.TransactionDefinition;
16
import org.springframework.transaction.TransactionStatus;
17
import org.springframework.transaction.annotation.Transactional;
18
import org.springframework.transaction.support.TransactionTemplate;
19
```
20
21
## Basic Usage
22
23
```java
24
// Declarative transaction management with @Transactional
25
@Transactional
26
public class UserService {
27
28
@Transactional(readOnly = true)
29
public User findUser(Long id) {
30
return userRepository.findById(id);
31
}
32
33
@Transactional(rollbackFor = Exception.class)
34
public User saveUser(User user) {
35
return userRepository.save(user);
36
}
37
}
38
39
// Programmatic transaction management with TransactionTemplate
40
@Service
41
public class OrderService {
42
43
private final TransactionTemplate transactionTemplate;
44
45
public OrderService(PlatformTransactionManager transactionManager) {
46
this.transactionTemplate = new TransactionTemplate(transactionManager);
47
}
48
49
public Order processOrder(Order order) {
50
return transactionTemplate.execute(status -> {
51
// Transactional operations
52
Order savedOrder = orderRepository.save(order);
53
notificationService.sendConfirmation(savedOrder);
54
return savedOrder;
55
});
56
}
57
}
58
```
59
60
## Architecture
61
62
Spring TX is built around several key components:
63
64
- **Core Transaction Management**: Central interfaces (`PlatformTransactionManager`, `TransactionDefinition`, `TransactionStatus`) providing vendor-neutral transaction abstraction
65
- **Declarative Transactions**: Annotation-based (`@Transactional`) and XML-based transaction demarcation using AOP
66
- **Programmatic Transactions**: Template-based (`TransactionTemplate`) and direct API access for explicit transaction control
67
- **Reactive Support**: Reactive transaction management for WebFlux applications using `ReactiveTransactionManager`
68
- **JTA Integration**: Enterprise transaction management with distributed transaction support
69
- **Exception Translation**: Comprehensive DAO exception hierarchy for consistent error handling across data access technologies
70
71
## Capabilities
72
73
### Core Transaction Management
74
75
Central interfaces and classes for imperative transaction management, providing the foundation for all transaction operations in Spring.
76
77
```java { .api }
78
public interface PlatformTransactionManager extends TransactionManager {
79
TransactionStatus getTransaction(@Nullable TransactionDefinition definition)
80
throws TransactionException;
81
void commit(TransactionStatus status) throws TransactionException;
82
void rollback(TransactionStatus status) throws TransactionException;
83
}
84
85
public interface TransactionDefinition {
86
int getPropagationBehavior();
87
int getIsolationLevel();
88
int getTimeout();
89
boolean isReadOnly();
90
@Nullable String getName();
91
}
92
93
public interface TransactionStatus extends TransactionExecution, SavepointManager, Flushable {
94
boolean hasSavepoint();
95
void flush();
96
}
97
```
98
99
[Core Transaction Management](./core-transaction-management.md)
100
101
### Declarative Transaction Management
102
103
Annotation-based and configuration-driven transaction management using AOP for clean separation of business logic and transaction concerns.
104
105
```java { .api }
106
@Target({ElementType.TYPE, ElementType.METHOD})
107
@Retention(RetentionPolicy.RUNTIME)
108
@Documented
109
public @interface Transactional {
110
String value() default "";
111
String transactionManager() default "";
112
Propagation propagation() default Propagation.REQUIRED;
113
Isolation isolation() default Isolation.DEFAULT;
114
int timeout() default TransactionDefinition.TIMEOUT_DEFAULT;
115
boolean readOnly() default false;
116
Class<? extends Throwable>[] rollbackFor() default {};
117
String[] rollbackForClassName() default {};
118
Class<? extends Throwable>[] noRollbackFor() default {};
119
String[] noRollbackForClassName() default {};
120
}
121
122
public enum Propagation {
123
REQUIRED, SUPPORTS, MANDATORY, REQUIRES_NEW, NOT_SUPPORTED, NEVER, NESTED
124
}
125
126
public enum Isolation {
127
DEFAULT, READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
128
}
129
```
130
131
[Declarative Transaction Management](./declarative-transactions.md)
132
133
### Programmatic Transaction Management
134
135
Template-based and direct API approaches for explicit transaction control when fine-grained transaction management is required.
136
137
```java { .api }
138
public class TransactionTemplate extends DefaultTransactionDefinition
139
implements TransactionOperations {
140
141
public TransactionTemplate(PlatformTransactionManager transactionManager);
142
143
@Nullable
144
public <T> T execute(TransactionCallback<T> action) throws TransactionException;
145
146
public void executeWithoutResult(TransactionCallbackWithoutResult action)
147
throws TransactionException;
148
}
149
150
@FunctionalInterface
151
public interface TransactionCallback<T> {
152
@Nullable
153
T doInTransaction(TransactionStatus status);
154
}
155
156
public abstract class TransactionCallbackWithoutResult implements TransactionCallback<Object> {
157
protected abstract void doInTransactionWithoutResult(TransactionStatus status);
158
}
159
```
160
161
[Programmatic Transaction Management](./programmatic-transactions.md)
162
163
### Reactive Transaction Management
164
165
Reactive transaction management support for WebFlux applications using non-blocking transaction operations.
166
167
```java { .api }
168
public interface ReactiveTransactionManager extends TransactionManager {
169
Mono<ReactiveTransaction> getReactiveTransaction(@Nullable TransactionDefinition definition);
170
Mono<Void> commit(ReactiveTransaction transaction);
171
Mono<Void> rollback(ReactiveTransaction transaction);
172
}
173
174
public interface TransactionalOperator {
175
static TransactionalOperator create(ReactiveTransactionManager transactionManager);
176
static TransactionalOperator create(ReactiveTransactionManager transactionManager,
177
TransactionDefinition transactionDefinition);
178
179
<T> Mono<T> transactional(Mono<T> mono);
180
<T> Flux<T> transactional(Flux<T> flux);
181
<T> Flux<T> execute(TransactionCallback<T> action) throws TransactionException;
182
}
183
184
public interface ReactiveTransaction extends TransactionExecution {
185
// Reactive transaction representation
186
}
187
188
@FunctionalInterface
189
public interface TransactionCallback<T> {
190
Publisher<T> doInTransaction(ReactiveTransaction status);
191
}
192
```
193
194
[Reactive Transaction Management](./reactive-transactions.md)
195
196
### Transaction Synchronization
197
198
Thread-safe transaction synchronization utilities for coordinating resources and callbacks within transaction boundaries.
199
200
```java { .api }
201
public abstract class TransactionSynchronizationManager {
202
public static boolean isSynchronizationActive();
203
public static void initSynchronization();
204
public static void registerSynchronization(TransactionSynchronization synchronization);
205
public static List<TransactionSynchronization> getSynchronizations();
206
public static void clearSynchronization();
207
208
public static boolean isCurrentTransactionReadOnly();
209
public static void setCurrentTransactionReadOnly(boolean readOnly);
210
@Nullable
211
public static String getCurrentTransactionName();
212
public static void setCurrentTransactionName(@Nullable String name);
213
214
public static boolean isActualTransactionActive();
215
public static void setActualTransactionActive(boolean active);
216
}
217
218
public interface TransactionSynchronization {
219
int STATUS_COMMITTED = 0;
220
int STATUS_ROLLED_BACK = 1;
221
int STATUS_UNKNOWN = 2;
222
223
default void suspend() {}
224
default void resume() {}
225
default void flush() {}
226
default void beforeCommit(boolean readOnly) {}
227
default void beforeCompletion() {}
228
default void afterCommit() {}
229
default void afterCompletion(int status) {}
230
}
231
```
232
233
[Transaction Synchronization](./transaction-synchronization.md)
234
235
### JTA Integration
236
237
Java Transaction API integration for distributed transaction management in enterprise environments.
238
239
```java { .api }
240
public class JtaTransactionManager extends AbstractPlatformTransactionManager {
241
public JtaTransactionManager();
242
public JtaTransactionManager(UserTransaction userTransaction);
243
public JtaTransactionManager(UserTransaction userTransaction,
244
TransactionManager transactionManager);
245
246
public void setUserTransaction(UserTransaction userTransaction);
247
public UserTransaction getUserTransaction();
248
public void setTransactionManager(TransactionManager transactionManager);
249
public TransactionManager getTransactionManager();
250
251
public void setAllowCustomIsolationLevels(boolean allowCustomIsolationLevels);
252
public void setGlobalRollbackOnParticipationFailure(boolean globalRollbackOnParticipationFailure);
253
}
254
255
public interface TransactionFactory {
256
Transaction createTransaction(@Nullable String name, int timeout) throws NotSupportedException,
257
SystemException;
258
}
259
260
public class UserTransactionAdapter implements UserTransaction {
261
public UserTransactionAdapter(TransactionManager transactionManager);
262
// UserTransaction method implementations
263
}
264
```
265
266
[JTA Integration](./jta-integration.md)
267
268
### Data Access Exception Translation
269
270
Comprehensive exception hierarchy providing consistent error handling across different data access technologies.
271
272
```java { .api }
273
public abstract class DataAccessException extends NestedRuntimeException {
274
public DataAccessException(String msg);
275
public DataAccessException(String msg, @Nullable Throwable cause);
276
}
277
278
// Key exception types
279
public class DataIntegrityViolationException extends NonTransientDataAccessException {}
280
public class DataRetrievalFailureException extends NonTransientDataAccessException {}
281
public class DeadlockLoserDataAccessException extends PessimisticLockingFailureException {}
282
public class DuplicateKeyException extends DataIntegrityViolationException {}
283
public class OptimisticLockingFailureException extends ConcurrencyFailureException {}
284
public class PessimisticLockingFailureException extends ConcurrencyFailureException {}
285
public class QueryTimeoutException extends TransientDataAccessException {}
286
287
public abstract class DataAccessUtils {
288
public static <T> T singleResult(@Nullable Collection<T> results)
289
throws IncorrectResultSizeDataAccessException;
290
public static <T> T requiredSingleResult(@Nullable Collection<T> results)
291
throws IncorrectResultSizeDataAccessException;
292
public static <T> T uniqueResult(@Nullable Collection<T> results)
293
throws IncorrectResultSizeDataAccessException;
294
}
295
```
296
297
[Data Access Exception Translation](./dao-exceptions.md)
298
299
### Transactional Events
300
301
Event listener support that coordinates with transaction lifecycle for reliable event processing.
302
303
```java { .api }
304
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
305
@Retention(RetentionPolicy.RUNTIME)
306
@Documented
307
@EventListener
308
public @interface TransactionalEventListener {
309
TransactionPhase phase() default TransactionPhase.AFTER_COMMIT;
310
String condition() default "";
311
boolean fallbackExecution() default false;
312
String id() default "";
313
}
314
315
public enum TransactionPhase {
316
BEFORE_COMMIT, AFTER_COMMIT, AFTER_ROLLBACK, AFTER_COMPLETION
317
}
318
319
public interface TransactionalApplicationListener<E extends ApplicationEvent>
320
extends ApplicationListener<E> {
321
TransactionPhase getTransactionPhase();
322
boolean getFallbackExecution();
323
}
324
```
325
326
[Transactional Events](./transactional-events.md)
327
328
## Core Types
329
330
```java { .api }
331
// Core interfaces
332
public interface TransactionManager {} // Marker interface
333
334
public interface TransactionExecution {
335
boolean isNewTransaction();
336
void setRollbackOnly();
337
boolean isRollbackOnly();
338
boolean isCompleted();
339
}
340
341
public interface SavepointManager {
342
Object createSavepoint() throws TransactionException;
343
void rollbackToSavepoint(Object savepoint) throws TransactionException;
344
void releaseSavepoint(Object savepoint) throws TransactionException;
345
}
346
347
// Transaction definition constants
348
public interface TransactionDefinition {
349
int PROPAGATION_REQUIRED = 0;
350
int PROPAGATION_SUPPORTS = 1;
351
int PROPAGATION_MANDATORY = 2;
352
int PROPAGATION_REQUIRES_NEW = 3;
353
int PROPAGATION_NOT_SUPPORTED = 4;
354
int PROPAGATION_NEVER = 5;
355
int PROPAGATION_NESTED = 6;
356
357
int ISOLATION_DEFAULT = -1;
358
int ISOLATION_READ_UNCOMMITTED = 1;
359
int ISOLATION_READ_COMMITTED = 2;
360
int ISOLATION_REPEATABLE_READ = 4;
361
int ISOLATION_SERIALIZABLE = 8;
362
363
int TIMEOUT_DEFAULT = -1;
364
}
365
366
// Exception hierarchy
367
public abstract class TransactionException extends NestedRuntimeException {
368
public TransactionException(String msg);
369
public TransactionException(String msg, @Nullable Throwable cause);
370
}
371
372
public class CannotCreateTransactionException extends TransactionException {}
373
public class IllegalTransactionStateException extends TransactionException {}
374
public class UnexpectedRollbackException extends TransactionException {}
375
public class TransactionSystemException extends TransactionException {}
376
public class TransactionTimedOutException extends TransactionException {}
377
```