transactional不会在SpringBoot中使用数据jpa回滚选中的异常

yr9zkbsy  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(504)

我有一个 ProcessRecon 使用一个名为 execute . 它保存一个实体 Reconciliation 使用 paymentRepository.saveRecon 并使用 paymentRepository.sendReconAck .
现在这个外部web服务可能会失败,在这种情况下,我想回滚更改,即保存的实体。因为我使用的是unirest,所以它抛出unirestexception,这是一个选中的异常。
控制台上没有错误,但这可能会有帮助[更新]。

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

我现在看到的是,即使存在 UnirestException . 但我不希望数据被保存到数据库中。
我在MySQL5.7中使用SpringBoot2.3.3。这是我的密码。
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);
        }
    }
}

对账数据源.java

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

pbwdgjma1#

为了使注解工作,您必须使用接口而不是类来进行依赖注入。

interface ProcessRecon {
      Reconciliation execute(final Reconciliation reconciliation) 
          throws UnirestException;
}

然后

@Usecase
public class ProcessReconImpl implements ProcessRecon {

    private final PaymentRepository paymentRepository;

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

    @Transactional(rollbackFor = UnirestException.class)
    public Reconciliation execute(final Reconciliation reconciliation) throws UnirestException {
        //method implementation...
    }
}

使用

@Autowired
ProcessRecon processRecon;

public void executeServiceMethod(Reconciliation reconciliation) {
    processRecon.execute(reconciliation)
}

这样你就有了 ProcessReconImpl 注解提供了附加功能。

w3nuxt5m

w3nuxt5m2#

我假设表的默认引擎是innodb,但令我惊讶的是,这些表是使用不支持事务的myisam引擎创建的。
我通过使用下面的属性解决了这个问题

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

而不是

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

这是唯一需要的改变。谢谢!

相关问题