首页 > 解决方案 > 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() 开始新的交易?

标签: javaspringspring-boottransactionsspring-transactions

解决方案


这很简单。通过“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;
}

推荐阅读