0
# Core Transaction Management
1
2
Spring's core transaction management provides the foundational interfaces and classes for imperative transaction control. These components form the basis for all transaction operations in Spring applications.
3
4
## Core Interfaces
5
6
### PlatformTransactionManager
7
8
The central interface for imperative transaction infrastructure in Spring applications.
9
10
```java { .api }
11
public interface PlatformTransactionManager extends TransactionManager {
12
/**
13
* Return a currently active transaction or create a new one.
14
* @param definition TransactionDefinition instance describing propagation behavior,
15
* isolation level, timeout etc. (can be null for defaults)
16
* @return transaction status object representing the new or current transaction
17
* @throws TransactionException in case of lookup, creation, or system errors
18
*/
19
TransactionStatus getTransaction(@Nullable TransactionDefinition definition)
20
throws TransactionException;
21
22
/**
23
* Commit the given transaction, with regard to its status.
24
* @param status object returned by the getTransaction method
25
* @throws TransactionException in case of commit or system errors
26
*/
27
void commit(TransactionStatus status) throws TransactionException;
28
29
/**
30
* Perform a rollback of the given transaction.
31
* @param status object returned by the getTransaction method
32
* @throws TransactionException in case of system errors
33
*/
34
void rollback(TransactionStatus status) throws TransactionException;
35
}
36
```
37
38
### TransactionDefinition
39
40
Interface that defines Spring-compliant transaction properties including propagation behavior, isolation level, timeout, and read-only flag.
41
42
```java { .api }
43
public interface TransactionDefinition {
44
// Propagation constants
45
int PROPAGATION_REQUIRED = 0;
46
int PROPAGATION_SUPPORTS = 1;
47
int PROPAGATION_MANDATORY = 2;
48
int PROPAGATION_REQUIRES_NEW = 3;
49
int PROPAGATION_NOT_SUPPORTED = 4;
50
int PROPAGATION_NEVER = 5;
51
int PROPAGATION_NESTED = 6;
52
53
// Isolation constants
54
int ISOLATION_DEFAULT = -1;
55
int ISOLATION_READ_UNCOMMITTED = 1;
56
int ISOLATION_READ_COMMITTED = 2;
57
int ISOLATION_REPEATABLE_READ = 4;
58
int ISOLATION_SERIALIZABLE = 8;
59
60
// Timeout constant
61
int TIMEOUT_DEFAULT = -1;
62
63
/**
64
* Return the propagation behavior. Must return one of the PROPAGATION_XXX constants.
65
* @return the propagation behavior
66
*/
67
default int getPropagationBehavior() { return PROPAGATION_REQUIRED; }
68
69
/**
70
* Return the isolation level. Must return one of the ISOLATION_XXX constants.
71
* @return the isolation level
72
*/
73
default int getIsolationLevel() { return ISOLATION_DEFAULT; }
74
75
/**
76
* Return the transaction timeout.
77
* @return the transaction timeout
78
*/
79
default int getTimeout() { return TIMEOUT_DEFAULT; }
80
81
/**
82
* Return whether to optimize as a read-only transaction.
83
* @return true if the transaction is to be optimized as read-only
84
*/
85
default boolean isReadOnly() { return false; }
86
87
/**
88
* Return the name of this transaction.
89
* @return the name of this transaction (null by default)
90
*/
91
@Nullable
92
default String getName() { return null; }
93
94
/**
95
* Return an unmodifiable TransactionDefinition with defaults.
96
* @return TransactionDefinition with default values
97
*/
98
static TransactionDefinition withDefaults() {
99
return StaticTransactionDefinition.INSTANCE;
100
}
101
}
102
```
103
104
### TransactionStatus
105
106
Representation of an ongoing transaction that extends common TransactionExecution interface and provides access to savepoint management.
107
108
```java { .api }
109
public interface TransactionStatus extends TransactionExecution, SavepointManager, Flushable {
110
/**
111
* Return whether this transaction internally carries a savepoint.
112
* @return true if this transaction carries a savepoint
113
*/
114
default boolean hasSavepoint() { return false; }
115
116
/**
117
* Flush the underlying session to the datastore, if applicable.
118
*/
119
@Override
120
default void flush() {}
121
}
122
123
public interface TransactionExecution {
124
/**
125
* Return whether this is a new transaction.
126
* @return true if this is a new transaction
127
*/
128
boolean isNewTransaction();
129
130
/**
131
* Set the transaction rollback-only.
132
*/
133
void setRollbackOnly();
134
135
/**
136
* Return whether the transaction has been marked as rollback-only.
137
* @return true if the transaction is rollback-only
138
*/
139
boolean isRollbackOnly();
140
141
/**
142
* Return whether this transaction is completed.
143
* @return true if the transaction is completed
144
*/
145
boolean isCompleted();
146
}
147
148
public interface SavepointManager {
149
/**
150
* Create a new savepoint.
151
* @return savepoint object
152
* @throws TransactionException if savepoint creation failed
153
*/
154
Object createSavepoint() throws TransactionException;
155
156
/**
157
* Roll back to the given savepoint.
158
* @param savepoint savepoint to roll back to
159
* @throws TransactionException if rollback failed
160
*/
161
void rollbackToSavepoint(Object savepoint) throws TransactionException;
162
163
/**
164
* Explicitly release the given savepoint.
165
* @param savepoint savepoint to release
166
* @throws TransactionException if release failed
167
*/
168
void releaseSavepoint(Object savepoint) throws TransactionException;
169
}
170
```
171
172
## Implementation Classes
173
174
### DefaultTransactionDefinition
175
176
Mutable implementation of TransactionDefinition with setter methods for all transaction properties.
177
178
```java { .api }
179
public class DefaultTransactionDefinition implements TransactionDefinition, Serializable {
180
public DefaultTransactionDefinition();
181
public DefaultTransactionDefinition(TransactionDefinition other);
182
public DefaultTransactionDefinition(int propagationBehavior);
183
184
public void setPropagationBehavior(int propagationBehavior);
185
public void setIsolationLevel(int isolationLevel);
186
public void setTimeout(int timeout);
187
public void setReadOnly(boolean readOnly);
188
public void setName(String name);
189
190
// TransactionDefinition method implementations
191
public int getPropagationBehavior();
192
public int getIsolationLevel();
193
public int getTimeout();
194
public boolean isReadOnly();
195
@Nullable
196
public String getName();
197
}
198
```
199
200
### AbstractPlatformTransactionManager
201
202
Abstract base class for PlatformTransactionManager implementations that provides common transaction handling logic.
203
204
```java { .api }
205
public abstract class AbstractPlatformTransactionManager
206
implements PlatformTransactionManager, ConfigurableTransactionManager, Serializable {
207
208
// Synchronization constants
209
public static final int SYNCHRONIZATION_ALWAYS = 0;
210
public static final int SYNCHRONIZATION_ON_ACTUAL_TRANSACTION = 1;
211
public static final int SYNCHRONIZATION_NEVER = 2;
212
213
public AbstractPlatformTransactionManager();
214
215
// Configuration methods
216
public void setTransactionSynchronization(int transactionSynchronization);
217
public int getTransactionSynchronization();
218
public void setDefaultTimeout(int defaultTimeout);
219
public int getDefaultTimeout();
220
public void setNestedTransactionAllowed(boolean nestedTransactionAllowed);
221
public boolean isNestedTransactionAllowed();
222
public void setValidateExistingTransaction(boolean validateExistingTransaction);
223
public boolean isValidateExistingTransaction();
224
public void setGlobalRollbackOnParticipationFailure(boolean globalRollbackOnParticipationFailure);
225
public boolean isGlobalRollbackOnParticipationFailure();
226
public void setFailEarlyOnGlobalRollbackOnly(boolean failEarlyOnGlobalRollbackOnly);
227
public boolean isFailEarlyOnGlobalRollbackOnly();
228
public void setRollbackOnCommitFailure(boolean rollbackOnCommitFailure);
229
public boolean isRollbackOnCommitFailure();
230
231
// PlatformTransactionManager implementation
232
@Override
233
public final TransactionStatus getTransaction(@Nullable TransactionDefinition definition)
234
throws TransactionException;
235
@Override
236
public final void commit(TransactionStatus status) throws TransactionException;
237
@Override
238
public final void rollback(TransactionStatus status) throws TransactionException;
239
240
// Template methods for subclasses
241
protected abstract Object doGetTransaction() throws TransactionException;
242
protected boolean isExistingTransaction(Object transaction) throws TransactionException;
243
protected abstract void doBegin(Object transaction, TransactionDefinition definition)
244
throws TransactionException;
245
protected Object doSuspend(Object transaction) throws TransactionException;
246
protected void doResume(@Nullable Object transaction, Object suspendedTransaction)
247
throws TransactionException;
248
protected boolean shouldCommitOnGlobalRollbackOnly();
249
protected abstract void doCommit(DefaultTransactionStatus status) throws TransactionException;
250
protected abstract void doRollback(DefaultTransactionStatus status) throws TransactionException;
251
protected void doSetRollbackOnly(DefaultTransactionStatus status) throws TransactionException;
252
protected void registerAfterCompletionWithExistingTransaction(Object transaction,
253
List<TransactionSynchronization> synchronizations) throws TransactionException;
254
protected void doCleanupAfterCompletion(Object transaction);
255
}
256
```
257
258
## Configuration Interfaces
259
260
### ConfigurableTransactionManager
261
262
Interface for transaction managers that allow configuration of transaction execution listeners.
263
264
```java { .api }
265
public interface ConfigurableTransactionManager extends PlatformTransactionManager {
266
/**
267
* Add a transaction execution listener.
268
* @param listener the listener to add
269
*/
270
void addListener(TransactionExecutionListener listener);
271
272
/**
273
* Remove a transaction execution listener.
274
* @param listener the listener to remove
275
*/
276
void removeListener(TransactionExecutionListener listener);
277
}
278
```
279
280
### TransactionExecutionListener
281
282
Listener interface for transaction execution events.
283
284
```java { .api }
285
public interface TransactionExecutionListener {
286
/**
287
* Called when a transaction begins.
288
* @param transactionExecution transaction execution details
289
*/
290
default void beforeBegin(TransactionExecution transactionExecution) {}
291
292
/**
293
* Called after a transaction begins successfully.
294
* @param transactionExecution transaction execution details
295
*/
296
default void afterBegin(TransactionExecution transactionExecution) {}
297
298
/**
299
* Called before transaction commit.
300
* @param transactionExecution transaction execution details
301
*/
302
default void beforeCommit(TransactionExecution transactionExecution) {}
303
304
/**
305
* Called after successful transaction commit.
306
* @param transactionExecution transaction execution details
307
*/
308
default void afterCommit(TransactionExecution transactionExecution) {}
309
310
/**
311
* Called before transaction rollback.
312
* @param transactionExecution transaction execution details
313
*/
314
default void beforeRollback(TransactionExecution transactionExecution) {}
315
316
/**
317
* Called after transaction rollback.
318
* @param transactionExecution transaction execution details
319
*/
320
default void afterRollback(TransactionExecution transactionExecution) {}
321
}
322
```
323
324
## Usage Examples
325
326
### Basic Transaction Manager Usage
327
328
```java
329
@Service
330
public class AccountService {
331
332
private final PlatformTransactionManager transactionManager;
333
private final AccountRepository accountRepository;
334
335
public AccountService(PlatformTransactionManager transactionManager,
336
AccountRepository accountRepository) {
337
this.transactionManager = transactionManager;
338
this.accountRepository = accountRepository;
339
}
340
341
public void transferMoney(Long fromId, Long toId, BigDecimal amount) {
342
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
343
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
344
def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
345
def.setTimeout(30);
346
347
TransactionStatus status = transactionManager.getTransaction(def);
348
349
try {
350
Account fromAccount = accountRepository.findById(fromId);
351
Account toAccount = accountRepository.findById(toId);
352
353
fromAccount.debit(amount);
354
toAccount.credit(amount);
355
356
accountRepository.save(fromAccount);
357
accountRepository.save(toAccount);
358
359
transactionManager.commit(status);
360
} catch (Exception e) {
361
transactionManager.rollback(status);
362
throw e;
363
}
364
}
365
}
366
```
367
368
### Custom Transaction Definition
369
370
```java
371
public class CustomTransactionDefinition implements TransactionDefinition {
372
373
private final int propagationBehavior;
374
private final int isolationLevel;
375
private final int timeout;
376
private final boolean readOnly;
377
private final String name;
378
379
public CustomTransactionDefinition(int propagationBehavior, int isolationLevel,
380
int timeout, boolean readOnly, String name) {
381
this.propagationBehavior = propagationBehavior;
382
this.isolationLevel = isolationLevel;
383
this.timeout = timeout;
384
this.readOnly = readOnly;
385
this.name = name;
386
}
387
388
@Override
389
public int getPropagationBehavior() {
390
return propagationBehavior;
391
}
392
393
@Override
394
public int getIsolationLevel() {
395
return isolationLevel;
396
}
397
398
@Override
399
public int getTimeout() {
400
return timeout;
401
}
402
403
@Override
404
public boolean isReadOnly() {
405
return readOnly;
406
}
407
408
@Override
409
public String getName() {
410
return name;
411
}
412
}
413
```
414
415
### Savepoint Usage
416
417
```java
418
@Service
419
public class OrderService {
420
421
private final PlatformTransactionManager transactionManager;
422
423
public void processComplexOrder(Order order) {
424
TransactionStatus status = transactionManager.getTransaction(
425
TransactionDefinition.withDefaults());
426
427
try {
428
// Process main order
429
processOrder(order);
430
431
// Create savepoint before risky operation
432
Object savepoint = status.createSavepoint();
433
434
try {
435
// Attempt risky operation
436
processSpecialItems(order);
437
} catch (SpecialItemException e) {
438
// Rollback to savepoint and continue with main transaction
439
status.rollbackToSavepoint(savepoint);
440
log.warn("Special item processing failed, continuing without special items", e);
441
} finally {
442
// Release savepoint
443
status.releaseSavepoint(savepoint);
444
}
445
446
// Complete transaction
447
transactionManager.commit(status);
448
} catch (Exception e) {
449
transactionManager.rollback(status);
450
throw e;
451
}
452
}
453
}
454
```
455
456
## Exception Handling
457
458
The core transaction management components throw various TransactionException subtypes:
459
460
```java { .api }
461
public abstract class TransactionException extends NestedRuntimeException {
462
public TransactionException(String msg);
463
public TransactionException(String msg, @Nullable Throwable cause);
464
}
465
466
public class CannotCreateTransactionException extends TransactionException {}
467
public class IllegalTransactionStateException extends TransactionException {}
468
public class UnexpectedRollbackException extends TransactionException {}
469
public class HeuristicCompletionException extends TransactionException {}
470
public class TransactionSystemException extends TransactionException {}
471
public class TransactionTimedOutException extends TransactionException {}
472
public class TransactionSuspensionNotSupportedException extends TransactionException {}
473
public class NestedTransactionNotSupportedException extends TransactionException {}
474
public class NoTransactionException extends TransactionException {}
475
```
476
477
These exceptions provide detailed information about transaction failures and allow applications to handle different error scenarios appropriately.