0
# Reactive Transaction Management
1
2
Spring's reactive transaction management provides non-blocking transaction support for WebFlux applications using reactive streams and operators.
3
4
## Core Interfaces
5
6
### ReactiveTransactionManager
7
8
```java { .api }
9
public interface ReactiveTransactionManager extends TransactionManager {
10
Mono<ReactiveTransaction> getReactiveTransaction(@Nullable TransactionDefinition definition);
11
Mono<Void> commit(ReactiveTransaction transaction);
12
Mono<Void> rollback(ReactiveTransaction transaction);
13
}
14
```
15
16
### TransactionalOperator
17
18
```java { .api }
19
public interface TransactionalOperator {
20
static TransactionalOperator create(ReactiveTransactionManager transactionManager);
21
static TransactionalOperator create(ReactiveTransactionManager transactionManager,
22
TransactionDefinition transactionDefinition);
23
24
<T> Mono<T> transactional(Mono<T> mono);
25
<T> Flux<T> transactional(Flux<T> flux);
26
<T> Flux<T> execute(TransactionCallback<T> action) throws TransactionException;
27
}
28
29
@FunctionalInterface
30
public interface TransactionCallback<T> {
31
Publisher<T> doInTransaction(ReactiveTransaction status);
32
}
33
34
public interface ReactiveTransaction extends TransactionExecution {
35
// Reactive transaction representation
36
}
37
```
38
39
## Usage Examples
40
41
```java
42
@Service
43
public class ReactiveUserService {
44
45
private final TransactionalOperator transactionalOperator;
46
private final ReactiveUserRepository userRepository;
47
48
public ReactiveUserService(ReactiveTransactionManager transactionManager,
49
ReactiveUserRepository userRepository) {
50
this.transactionalOperator = TransactionalOperator.create(transactionManager);
51
this.userRepository = userRepository;
52
}
53
54
public Mono<User> createUser(User user) {
55
return userRepository.save(user)
56
.as(transactionalOperator::transactional);
57
}
58
59
public Flux<User> createUsers(Flux<User> users) {
60
return users
61
.flatMap(userRepository::save)
62
.as(transactionalOperator::transactional);
63
}
64
65
// Using execute with callback for more complex transactions
66
public Mono<User> updateUserWithCallback(Long userId, String newName) {
67
return transactionalOperator.execute(status -> {
68
return userRepository.findById(userId)
69
.flatMap(user -> {
70
user.setName(newName);
71
return userRepository.save(user);
72
})
73
.switchIfEmpty(Mono.error(new UserNotFoundException("User not found")));
74
}).singleOrEmpty();
75
}
76
}
77
```