2015-06-20 110 views
1

我已經閱讀了很多關於spring事務的stackoverflow頁面。 我的春季交易配置是春季交易只是在進入服務方式嗎?

<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> 

我的服務是這樣的。

@Service 
public class TestServiceImpl implements TestService { 
    @Override 
    public void testRollback() { 
      testRollbackSecondLevel(); 
    } 

    @Transactional 
    @Override 
    public void testRollbackSecondLevel() { 
     // any update sql in here 
     carCostService.testUpdate(); 

     throw new RuntimeException(); 
    } 
} 

然後我寫一個測試類來測試,在我的測試代碼,當我使用

// this test is not roll back, and the Transactional even not created 
@Test 
public void testTransactional() { 
    // use this function, the Transactional don't work 
    interCityService.testRollback(); 
} 

// this test is roll back successfully 
@Test 
public void testTransactionalSecondLevel() { 
    // but if I use the second level function instead of the first function, 
    // the Transactional works fine, and the data can roll back 
    interCityService.testRollbackSecondLevel(); 
} 

我調試的代碼,當我使用的第一個測試,交易甚至不會被創建。第二個可以成功創建事務。

我使用sql來判斷事務是否存在。

SELECT * FROM INFORMATION_SCHEMA.INNODB_TRX\G 

如果sql返回空集,那麼沒有事務被創建。

那麼問題是什麼?提前致謝。

我使用春季版4.1.2.RELEASE。

回答

0

如果你希望你所有的方法服務事務添加事務標註爲類,而不是方法級

@Transactional 
@Service 
public class TestServiceImpl implements TestService { 

    @Override 
    public void testRollback() { 
     testRollbackSecondLevel(); 
    } 


@Override 
public void testRollbackSecondLevel() { 
    // any update sql in here 
    carCostService.testUpdate(); 

    throw new RuntimeException(); 
} 
} 

而且,因爲他們已經解釋說你已經有一筆交易不能在同一個服務中開始。所以,如果你想使第一個方法事務處理,你必須從你的服務之外調用。