java - Spring 声明式事务中的传播(选择正确)问题

标签 java spring spring-boot transactions spring-transactions

我对 @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;
}

关于java - Spring 声明式事务中的传播(选择正确)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56396262/

相关文章:

java - 使用 Eclipse 的 ClassNotFoundException/NoClassDefFoundError

java - 返回第一个结束任务的Java中的任务执行器

java - 如何解析这种格式的Joda时间

spring - 使用 Swagger/OpenAPI 文档模拟 Rest API

java - JDBC 访问被拒绝错误

java - 如何使用 Mono & Flux 限制并发 http 请求

java - Java 文件中的 Spring 国际化错误

spring - 如何在 Spring 中使用 javax.validation.constraints 验证 List 内元素的长度

java - 无法将文件从一个服务器上传到另一个服务器

Spring Security 5 OAuth2 客户端与 Gitlab 失败