Search code examples
javaspring-boottransactionsunirest

Transactional doesn't roll back on checked exception in Spring Boot with Data JPA


I have a ProcessRecon usecase class with a single method named execute. It saves an entity Reconciliation using paymentRepository.saveRecon and calls a web service as part of acknowledgement using paymentRepository.sendReconAck.

Now there's a chance that this external web service might fail in which case I want to rollback the changes i.e. the saved entity. Since I am using Unirest, it throws UnirestException which is a checked exception.

There are no errors on the console but this will probably be helpful [UPDATED].

2020-08-20 17:21:42,035 DEBUG [http-nio-7012-exec-6] org.springframework.transaction.support.AbstractPlatformTransactionManager: Creating new transaction with name [com.eyantra.payment.features.payment.domain.usecases.ProcessRecon.execute]:PROPAGATION_REQUIRED,ISOLATION_DEFAULT,-com.mashape.unirest.http.exceptions.UnirestException
...
2020-08-20 17:21:44,041 DEBUG [http-nio-7012-exec-2] org.springframework.transaction.support.AbstractPlatformTransactionManager: Initiating transaction rollback
2020-08-20 17:21:44,044 DEBUG [http-nio-7012-exec-2] org.springframework.orm.jpa.JpaTransactionManager: Rolling back JPA transaction on EntityManager [SessionImpl(621663440<open>)]
2020-08-20 17:21:44,059 DEBUG [http-nio-7012-exec-2] org.springframework.orm.jpa.JpaTransactionManager: Not closing pre-bound JPA EntityManager after transaction
2020-08-20 17:22:40,020 DEBUG [http-nio-7012-exec-2] org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor: Closing JPA EntityManager in OpenEntityManagerInViewInterceptor

What I see at the moment is that entity gets pushed to database even if there's a UnirestException. But I expect no data be saved to database.

I am using Spring Boot 2.3.3 with MySQL 5.7. This is the code I have for it.

ProcessRecon.java

@Usecase // this custom annotation is derived from @service
public class ProcessRecon {

    private final PaymentRepository paymentRepository;

    @Autowired
    public ProcessRecon(PaymentRepository paymentRepository) {
        this.paymentRepository = paymentRepository;
    }

    @Transactional(rollbackFor = UnirestException.class)
    public Reconciliation execute(final Reconciliation reconciliation) throws UnirestException {
        
        PaymentDetails paymentDetails = paymentRepository.getByReqId(reconciliation.getReqId());

        if (paymentDetails == null)
            throw new EntityNotFoundException(ExceptionMessages.PAYMENT_DETAILS_NOT_FOUND);
        reconciliation.setPaymentDetails(paymentDetails);

        Long transId = null;
        if (paymentDetails.getImmediateResponse() != null)
            transId = paymentDetails.getImmediateResponse().getTransId();

        if (transId != null)
            reconciliation.setTransId(transId);

        if (reconciliation.getTransId() == null)
            throw new ValidationException("transId should be provided in Reconciliation if there is no immediate" +
                    " response for a particular reqId!");

        // THIS GETS SAVED
        Reconciliation savedRecon = paymentRepository.saveRecon(reconciliation);
        paymentDetails.setReconciliation(savedRecon);
        
        // IF THROWS SOME ERROR, ROLLBACK
        paymentRepository.sendReconAck(reconciliation);
        return savedRecon;
    }
}

PaymentRepositoryImpl.java

@CleanRepository
public class PaymentRepositoryImpl implements PaymentRepository {

    @Override
    public String sendReconAck(final Reconciliation recon) throws UnirestException {
        // Acknowledge OP
        return sendAck(recon.getRequestType(), recon.getTransId());
    }

    String sendAck(final String requestType, final Long transId) throws UnirestException {
        // TODO: Check if restTemplate can work with characters (requestType)
        final Map<String, Object> queryParams = new HashMap<String, Object>();
        queryParams.put("transId", transId);
        queryParams.put("requestType", requestType);

        logger.debug("{}", queryParams);

        final HttpResponse<String> result = Unirest.get(makeAckUrl()).queryString(queryParams).asString();

        logger.debug("Output of ack with queryParams {} is {}", queryParams, result.getBody());
        return result.getBody();
    }

    @Override
    public Reconciliation saveRecon(final Reconciliation recon) {
        try {
            return reconDS.save(recon);
        }
        catch (DataIntegrityViolationException ex) {
            throw new EntityExistsException(ExceptionMessages.CONSTRAINT_VIOLATION);
        }
    }
}

ReconciliationDatasource.java

@Datasource // extends from @Repository
public interface ReconciliationDatasource extends JpaRepository<Reconciliation, Long> {
    List<Reconciliation> findByPaymentDetails_User_Id(Long userId);
}

Solution

  • I assumed the default engine for the tables would be InnoDB but to my surpise, the tables were created using MyISAM engine which doesn't support transactions.

    I resolved the problem by using the below property as suggested here

    spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
    

    instead of

    spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
    

    That was the only change required. Thanks!