java - Spring中声明性事务中的传播(选择正确)问题
问题描述
我对@Transactional 注释中的传播有疑问。我需要在一种方法中进行两个操作,并且每个操作都应该在自己的事务中,然后进行提交。
@Service
@Transactional
public class FakturaServiceImpl implements FakturaService {
@Override
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public Integer przyjmijZaliczkeNaPodstPlatnosci(Integer platnoscId) {
Platnosc plat = Optional.ofNullable(platDao.findOne(platnoscId))
.orElseThrow(() -> new RecordNotExistsException("Platnosc", platnoscId));
// here should be beginning of transaction
Integer faktId = utworzFaktureZaliczkowaNaPodstPlatnosci(plat);
// commit
// start new transaction
rachotwMgr.dodajRachotwDlaZaliczekNaFakturze(faktId);
// commit
// ...
return faktId;
}
@Override
public Integer utworzFaktureZaliczkowaNaPodstPlatnosci(Platnosc plat) {
// Here not starting new transaction, it's still Propagation.NOT_SUPPORTED
rachotwMgr.naliczRachotwDlaRezerwacji(rezId, true); // this line is in new transaction
// Continue in Propagation.NOT_SUPPORTED
}
}
@Service
@Transactional
public class RachotwServiceImpl implements RachotwService {
@Override
@Transactional
public List<Rachotw> dodajRachotwDlaZaliczekNaFakturze(@NotNull Integer fakturaId) {
// Here starts new transaction..
}
}
我的想法是使用 Propagation.NOT_SUPPORTED 的一种方法和 Propagation.REQUIRED 内部的两种方法吗(在 utworzFaktureZaliczkowaNaPodstPlatnosci() 和 dodajRachotwDlaZaliczekNaFakturze() 应该提交之后)?
为什么具有 Propagation.REQUIRED (默认)的 utworzFaktureZaliczkowaNaPodstPlatnosci() 没有开始新事务,而 dodajRachotwDlaZaliczekNaFakturze() 和 naliczRachotwDlaRezerwacji() 开始新事务。如何让 utworzFaktureZaliczkowaNaPodstPlatnosci() 开始新的交易?
解决方案
这很简单。通过“FakturaServiceImpl”类声明,该方法utworzFaktureZaliczkowaNaPodstPlatnosci
确实支持事务,但前提是它将通过其他地方的 bean 声明调用:
@Inject
FakturaService service;
public void someMethod() {
// Transaction will be here
service.utworzFaktureZaliczkowaNaPodstPlatnosci(new Platnosc());
}
但是您只是对该方法进行简单调用,不涉及事务配置。
@Override
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public Integer przyjmijZaliczkeNaPodstPlatnosci(Integer platnoscId) {
.....
// Simple method call
Integer faktId = utworzFaktureZaliczkowaNaPodstPlatnosci(plat);
// ...
return faktId;
}
推荐阅读
- c# - 阅读 appsettings.json - 字段保持为空
- dynamics-nav-2013 - 如何使用或过滤
- python - 要列出的 Pandas 列名 - 正确的方法
- c# - 为什么 C# 不支持接口实现成员的隐式接口转换?
- php - 使用 Google Cloud API 获取用户权限
- ruby-on-rails - Rails:Shouda-matchers belongs_to 可选测试
- node.js - 从后端服务 (node.js) 使用 Microsoft Graph API
- windows - 可以在windows中复制一个git文件夹来管理多个分支吗?
- javascript - 来自 ng-repeat 的数组数据在多列和多行中,我该怎么做?
- android - 如何制作自定义 SMS 权限对话框