I am using Spring boot 2.4.4 with Webflux. My use case is to rollback trnasaction on some condition.
Exposing a REST end point. On getting a request,
Code
@Transactional
public Mono<ServerResponse> submitOrder(final ServerRequest request) {
return request.bodyToMono(OrderDto.class).flatMap(orderDto -> {
return orderRepository.save(toOrder(orderDto)).flatMap(order -> {
return orderTestRepository
.saveAll(toOrderTestList(orderDto.getTestList())).collectList()
.flatMap(labTestRes -> {
// Need to rollback transaction if the below service call is not success
return removeService.submitOrder(orderDto, labOrder.getOrderId())
.flatMap(orderNum -> {
return noContent().build();
});
});
});
});
}
If your removeService
throws an exception on unsuccessful service call, modify your @Trasactional
to @Transactional(rollbackFor = ThatException.class)
. If not, throw a custom exception and change the annotation to @Transactional(rollbackFor = CustomException.class)
. You can also rollback for multiple exceptions like:
@Transactional(rollbackFor = { Exception1.class, Exception2.class })