spring - 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(....);
}
因为我循环,如果一个失败,我不想为每个人回滚。有更好的方法吗?
解决方案
这种方法应该很好用,尽管在某些情况下您可能需要@Transactional(propagation = Propagation.REQUIRES_NEW)
代替?
更程序化的方法曾经是 TransactionTemplate虽然我不确定是否有比这更新的方法。
推荐阅读
- c - 如何在 C 中将 10 位无符号字节数组转换为 uint16 字节数组?
- c# - C# - 每秒调用 30 次方法并创建屏幕截图“位图” - 屏幕录像机 FPS
- events - Laravel Eloquent 模型观察者删除方法抛出异常。怎么了?
- python - 扫雷算法,从起始方格打开所有相互接触的安全方格
- object - 无法在 Kotlin 中对象的超类构造函数中使用常量
- nvidia - 无法在每帧上获得 secondary1-nvinference-engine 和 secondary2-nvinference-engine 的结果
- django-rest-framework - 在返回 DRF 之前更改查询集
- github - 如何通过命令行从公共 github 存储库下载二进制文件?
- sql - OperationalError:尝试在 Google Cloud 应用程序上写入只读数据库
- node.js - 如何用变量替换所有内容?