CompletableFuture Transaction rollback

53 Views Asked by At

Given this pieace of code:

@Async
@Transactional
public CompletableFuture<Optional<Bundle>> newBundle(String name){
return CompletableFuture.supplyAsync(() -> {
    Bundle newBundle = bundleRepository.save(new Bundle(name));
    messageRepository.save(new Message("saved new bundle with name {}", name);
    return Optional.of(newBundle);
}).exceptionally(throwable -> {
    log.error(throwable.getMessage(), throwable);
    throw new IllegalArgumentException(throwable);
);
}

So when the call to

messageRepository.save(new Message("saved new bundle with name {}", name); fails,

will there be a rollback of

bundleRepository.save(new Bundle(name));

1

There are 1 best solutions below

0
Ken.Zhang On

The @Transactional annotation works by creating a proxy around the annotated method to manage the transaction. However, its effectiveness can depend on how and where the method is called, especially in asynchronous operations.

Given your code snippet, you're using @Async together with @Transactional on a method that returns a CompletableFuture.

Transactional Context: The @Transactional annotation creates a transactional context at the start of the method execution. Any operations that occur within this method are supposed to be part of this transactional context.

This means that these repository calls might not participate in the same transaction unless you explicitly configure method execution and transaction propagation to support this pattern.