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));
The
@Transactionalannotation 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
@Asynctogether with@Transactionalon a method that returns aCompletableFuture.Transactional Context: The
@Transactionalannotation 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.