首页 > 解决方案 > Spring数据事务循环

问题描述

我使用spring boot 2,带有spring data jpa和hibernate

在课堂上我有这个代码。

...

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

因为我循环,如果一个失败,我不想为每个人回滚。有更好的方法吗?

标签: springjpaspring-data-jpaspring-transactions

解决方案


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

更程序化的方法曾经是 TransactionTemplate虽然我不确定是否有比这更新的方法。


推荐阅读