Spring数据交易循环

时间:2019-05-02 14:27:06

标签: spring jpa spring-data-jpa spring-transactions

我使用带有弹簧数据jpa和休眠状态的spring boot 2

在课堂上我有这段代码。

...

private final MailContentBuilder mailContentBuilder;

private void sendEmail() {

    try {

        List<FactoryEmail> factoryEmails = prepareData();


        if (factoryEmails != null) {
            logger.info(String.valueOf(factoryEmails.size()) + " factories");
        }

        for (FactoryEmail factoryEmail : factoryEmails) {

            String message = mailContentBuilder.build(factoryEmail);

            if (factoryEmail.getEmails() != null && !factoryEmail.getEmails().isEmpty()) {

                logger.info("prepare to sent email to : " + factoryEmail.getFactoryName());

                mailService.sendHtmlMail(factoryEmail.getEmails(), "no conform", message);
                setSampleEmailSent(factoryEmail);

                Thread.sleep(5000);
            }
        }
    } catch (MessagingException | InterruptedException ex) {
        logger.error(ex.getMessage());
    }
}

private void setSampleEmailSent(FactoryEmail factoryEmail) {
    ...
    samplesServices.setEmailsSent(testSampleIdEmailSent);
}

在SampleService类中

@Transactional
public void setEmailsSent(Map<String, List<SampleId>> testSampleIdEmailSent) {
    ...
    repository.save(....);
}

因为我循环播放,如果失败了,我不想回滚所有人。有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

这种方法应该行之有效,尽管在某些情况下您可能需要@Transactional(propagation = Propagation.REQUIRES_NEW)来代替?

更具编程性的方法曾经是 TransactionTemplate,尽管我不确定是否有比此更新的方法。