使用@Transactional 注解有必要吗?弹簧靴

问题描述 投票:0回答:1

所以我是 Spring 新手,目前对

@Transactional
注释感到困惑,我已经阅读了很多关于这个主题的问题和答案,但似乎我仍然不明白。

这是我的问题:

  • 执行插入更新删除时需要

    @Transactional
    注解吗?当我试图证明这一点时,我仍然可以执行插入和更新。你知道为什么会这样吗?

  • 如果您使用或不使用

    @Transactional
    注释,是否会带来任何性能优势或问题?就像连接管理一样。

  • 如果我的程序中不使用

    @Transactional
    注解会发生什么?

  • 根据我使用

    @Transactional
    的经验,更新查询将在方法完成后刷新并提交,在某些情况下我不希望发生这种情况。例如:

@Transactional
private void doSomething() {
   TransactionEntity te = te.findById("");
   try {
      //fetch using feign and throw customTimCustomTimeoutException 
   } catch (CustomTimeoutException e) {
      te.workflowFailure("doSomething");
      repository.save(te);
   }
   //validation
   //business logic
   //save this save that
   //end of the method and changes will be flushed and committed
}

如果在方法结束时,数据库脱机,它会回滚,你会失去所有进度,对吗?即使在 catch 块语句中的

repository.save(te)
中,数据库可能没问题,并且您不想失去该进度。有什么解决办法或想法吗?

java spring spring-boot jpa spring-data-jpa
1个回答
4
投票
  1. 使用
    @Transactional
    接口时,不需要
    CrudRepository
    进行 CRUD 操作。默认情况下,所有这些方法都是事务性的。我猜你用的是这个。查看https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#transactions
  2. 当您将读取方法标记为
    @Transactional(readOnly = true)
    时,就会出现性能优势。例如,查看 SimpleJpaRepository
  3. 默认情况下,只有 CRUD 操作是事务性的。在其他情况下你必须使用
    @Transactional
    否则你会得到“java.lang.IllegalStateException: No transactional EntityManager available”。
  4. 这取决于您会得到什么样的例外。如果是运行时,您将获得回滚同意。但是,如果这是一个已检查的异常,您可以捕获它并决定是否要刷新数据。如果您对数据库进行了一些繁重的操作并且您不想失去此进度,您最终可以多次刷新,这取决于用例。
© www.soinside.com 2019 - 2024. All rights reserved.