Search code examples
spring-bootspring-webfluxspring-transactions

Spring boot rollback transaction on condition


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,

  1. Insert into order table
  2. Insert into order test table
  3. Call remote service to notify order
  4. Rollback order table and order test table entry on receiving error from the remove service.

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();
                                        });
                        });
            });

        });
    }

Solution

  • 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 })