实际上寻找PROPAGATION_NESTED(如果当前事务存在时在嵌套事务中执行)和PROPAGATION_Required(支持当前事务)之间的区别。
下面是简单的用例
在主类中我们调用method1并使用jdbc [Transaction1]创建客户。尚未提交。现在我们在主类中调用method2并为刚创建的客户[Transaction2]创建帐户。现在提交它。我们可以将事务2称为嵌套事务。
根据我的理解,如果我们将事务定义定义为PROPAGATION_NESTED
事务2将被视为嵌套,但如果我们将其定义为PROPAGATION_Required,它将支持当前事务。那么嵌套和必需的差异是什么?
答案 0 :(得分:7)
PROPAGATION_NESTED只能与DataSourceTransactionManager
和JDBC3驱动程序一起使用。它使用保存点以便能够回滚事务的某些部分(即,在Spring术语中构成嵌套事务的内容)。请参阅javadoc of Connection,了解保存点的工作原理。
要求完全不同。它只是意味着:如果已存在交易,请在此交易中完成工作;否则,启动新事务,完成工作并提交事务。
答案 1 :(得分:1)
因为您使用的是具有必需/嵌套传播的Spring,所以问题中提到的[Transaction1]和[Transaction2]是“相同的交易”。
作为用例,如果在method2()上使用“ required”
@Transaction(Require)
main() {
// throw new Exception(); => rollback all
method1();
method2();
// throw new Exception(); => rollback all
}
@Transaction(Require)
method1() {
// throw new Exception(); => rollback all
}
@Transaction(Require)
method2() {
// throw new Exception(); => rollback all
}
如果在method2()上使用嵌套
@Transaction(Require)
main() {
// throw new Exception(); => rollback all
method1();
// Create Save Point A
method2();
// Release Save Point A
// throw new Exception(); => rollback all
}
@Transaction(Require)
method1() {
// throw new Exception(); => rollback all
}
@Transaction(Nested) // is the same transaction as main
method2() {
// throw new Exception(); => will only rollback to Save Point A
}
嵌套交易的用例
(当一个客户需要一百万个帐户,并且需要几个小时才能完成所有任务时)
好处=>
一个帐户创建失败不会全部回滚(仅回滚失败帐户=>然后您可以启动调试)[节省公司有午夜批处理大量独立数据的时间]
< / li>它们都处于相同的连接/事务中[节省资源以比较需要新的资源]
例如:
@Transaction(Require)
main() {
// throw new Exception(); => rollback all
method1();
for(many time) {
// Create Save Point
method2();
// Release Save Point
}
// throw new Exception(); => rollback all (Be careful, it will rollback all!!!)
}
@Transaction(Require)
method1() {
// throw new Exception(); => rollback all
}
@Transaction(Nested) // is the same transaction as main
method2() {
// throw new Exception(); => will only rollback to Save Point
}