gpt4 book ai didi

java - Spring 3/Hibernate 中回滚事务的最佳实践

转载 作者:IT老高 更新时间:2023-10-28 13:50:54 25 4
gpt4 key购买 nike

引用 Spring documentation :

Any RuntimeException will trigger rollback, and any checked Exception will not

引用 javapractices.com

Unchecked exceptions :

  • represent defects in the program (bugs) - often invalid arguments passed to a non-private method. To quote from The Java Programming Language, by Gosling, Arnold, and Holmes : "Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time."
  • are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, or IllegalStateException
  • a method is not obliged to establish a policy for the unchecked exceptions thrown by its implementation (and they almost always do not do so)

Checked exceptions :

  • represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)
  • are subclasses of Exception
  • a method is obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow)

如果在我的业务逻辑过程中我发现了一个问题并且我想回滚更改,我必须抛出一个新的 RuntimeException 吗?它不是真正的 RuntimeException(未经检查的异常),因为我已经在逻辑中识别了它。还是我误解了这些概念?

我真正的问题,在我的@Transactional 服务方法中回滚事务的最佳做法是什么?

最佳答案

如果您使用检查异常,只需将它们添加到 @Transactional 注释的 rollbackFor 属性中。

@Transactional(rollbackFor = { MyInvalidUserException.class, MyApplicationException.class })
public void method() throws MyInvalidUserException, MyApplicationException {
...
...
}

等等

org.life.java 的 答案也可以正常工作。如果您想将程序化事务管理混合到您的声明性事务中或保持严格的声明性,这是一个学术决定。

关于java - Spring 3/Hibernate 中回滚事务的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4402506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com