Java Spring:理解@Transactional rollbackFor和事务划分
我假设以下堆栈跟踪为 java 调用:
B.method2 (annotated with a plain @Transactional)
A.method1 (annotated with a plain @Transactional)
Main.main (starting point of the call, with no current transaction)
我希望输入 A.method1 时启动事务 - 并且在离开 A.method1 时将提交(或回滚)事务。我还预计 B.method2 中将使用相同的事务。
从 B.method2 内部抛出 RuntimeException。这是默认情况下为 rollbackFor“列出”的异常。该异常在A.method1内被捕获,但在离开B.method2时会越过@Transactional的边界。
这是我的问题:(当前)事务是否会被标记为回滚?
I suppose the following stacktrace as java invocation:
B.method2 (annotated with a plain @Transactional)
A.method1 (annotated with a plain @Transactional)
Main.main (starting point of the call, with no current transaction)
I expect that a transaction is started when A.method1 is entered - and the transaction will be commited (or rolled back) when A.method1 is left. I also expect that the same transaction will be used within B.method2.
A RuntimeException is thrown from within B.method2. This is a Exception that is 'listed' for rollbackFor by default. The Exception is catched within A.method1, but it will pass the boundary of @Transactional when leaving B.method2.
This is my question: Will the (current) transaction be marked for rollback or not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认传播模式为
REQUIRED
,method2 将使用为 method1 启动的事务。出现异常时,该事务将被标记为回滚,因此不会向数据库提交任何内容。在 method1 之后,您可能会收到UnexpectedRollbackException
。这不是期望的行为,因为启动事务(拥有它)的代码应该控制回滚/提交。我会重新组织你的代码以避免这种可能性。
The default propagation mode is
REQUIRED
and method2 will use transaction started for method1. On exception this transaction will be marked for rollback, so nothing will be committed to the database. You may getUnexpectedRollbackException
after method1.This is not a desired behavior since code which started the transaction (owns it) should be in control of rollback/commit. I would reorganize your code to avoid such possibility.