我使用 Spring 并有两种使用声明性事务的方法......
在某些情况下methodA调用methodB ..我需要知道的是在声明性事务中提交是否发生两次......
例子
public void methodA() throws Exception {
this.transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED)
final Order order = this.transactionTemplate.execute(new TransactionCallback<Order>() {
@Override
public Order doInTransaction(TransactionStatus status) {
Order order = new Order();
String name = "Customer 2 " + (new Date()).toLocaleString();
order.setCustomer(name);
entityManager.persist(order);
..........................
.......................
// call methodB
methodB();
}
public void methodB() throws Exception {
this.transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
final Address add = this.transactionTemplate.execute(new TransactionCallback<Address >() {
@Override
public Order doInTransaction(TransactionStatus status) {
Address add= new Address ();
add.setAddress("address");
entityManager.persist(add);
......................
.....................
}
通过使用 PROPOGATION_REQUIRED,methodB 中的事务将加入 methodA 中启动的事务。
但这是否意味着事务被提交了两次?
我在 methodB 的事务中添加了同步器:
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization(){
public void afterCommit() {
System.out.println("====> AFTER SUCCESSFUL COMMIT 2 TO DB...");
}
我在 methodA 的事务中添加了同步器:
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization(){
public void afterCommit() {
System.out.println("====> AFTER SUCCESSFUL COMMIT 1 TO DB...");
}
我得到的输出是在方法A完成之后::
====> AFTER SUCCESSFUL COMMIT 2 TO DB...
====> AFTER SUCCESSFUL COMMIT 1 TO DB...
我想这意味着已经将两个同步器分配给了他的 trans..manager,并且当提交发生一次时......两个同步器都被调用了?......对吗?