支持传播的 Spring 事务
我想了解 Spring 事务与传播支持的用途。 java 文档提到,如果从事务中调用具有 @Transactional(propagation = Propagation.SUPPORTS) 的方法,则它支持该事务,但如果不存在事务,则该方法将以非事务方式执行。
这不是 Spring 事务的行为,与 Propagation.SUPPORTS 无关吗?
public class ServiceBean {
@Transactional(propagation = Propagation.SUPPORTS)
public void methodWithSupportsTx() {
//perform some database operations
}
}
public class OtherServiceBean {
@Transactional(propagation = Propagation.REQUIRED)
public void methodWithRequiredTx() {
//perform some database operations
serviceBean.methodWithSupportsTx();
}
}
在上面的代码示例中,无论 methodWithSupportsTx()
是否具有 @Transactional(propagation = Propagation.SUPPORTS)
注解,它都会在事务中执行,具体取决于 methodWithRequiredTx()
有 @Transactional
注释,对吧?
那么传播级别支持的需要/用途是什么?
I would like to understand the use of having a spring transaction with Propagation Supports. The java docs mention that if the method which has @Transactional(propagation = Propagation.SUPPORTS)
is called from within a transaction it supports the transaction but if no transaction exists, the method is executed non-transactionally.
Isn't this already the behavior of spring transactions irrespective of Propagation.SUPPORTS
?
public class ServiceBean {
@Transactional(propagation = Propagation.SUPPORTS)
public void methodWithSupportsTx() {
//perform some database operations
}
}
public class OtherServiceBean {
@Transactional(propagation = Propagation.REQUIRED)
public void methodWithRequiredTx() {
//perform some database operations
serviceBean.methodWithSupportsTx();
}
}
In the above code example, irrespective of whether methodWithSupportsTx()
has @Transactional(propagation = Propagation.SUPPORTS)
annotation it would be executed in a transaction depending on whether methodWithRequiredTx()
has @Transactional
annotation, right?
So what's the need/use of having a propagation level SUPPORTS?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 javadoc:
因此,这意味着,例如,在
methodWithSupportsTx()
内多次调用 Hibernate 的SessionFactory.getCurrentSession()
将返回相同的会话。From javadoc:
So, it means that, for example, multiple invocations of Hibernate's
SessionFactory.getCurrentSession()
insidemethodWithSupportsTx()
would return the same session.如果不存在所需的事务,则将创建一个新事务。因此,当您调用 serviceBean.methodWithSupportsTx() 时,将进行一个新事务。如果你的方法确实是事务性的,如果不存在事务,你将会看到来自 spring 的错误。
A required transaction will create a new transaction if none exists. Therefore a new transaction would be made when you call serviceBean.methodWithSupportsTx(). If your method is truly transactional you will see an error from spring if no transaction exists.