【问题标题】:Spring data transaction loopSpring数据事务循环
【发布时间】:2019-05-02 14:27:06
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      • 2012-10-28
      • 1970-01-01
      • 2011-07-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-29
      相关资源
      最近更新 更多