spring事务是否只在进入服务方法中起作用?

Is spring transaction is only working in entering service method?

我已经阅读了很多关于 spring 交易的 Whosebug 页面。 我的 spring 交易配置是

<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();
    }
}

然后我写一个测试class来测试,在我的测试代码中,当我使用

// 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 return 空集,则没有创建交易。

所以问题是什么?提前致谢。

我使用的是spring版本4.1.2.RELEASE.

spring @Transactional 使用代理工作,这意味着从同一个 class 使用此注释调用方法没有任何影响 == @Transactional 将被忽略。有很多关于它的主题,请在这里查看更深入的解释:Spring @Transaction method call by the method within the same class, does not work?

如果您希望所有方法服务都是事务性的,请将事务性注释添加为 class 而不是方法级别

@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();
 }
} 

此外,正如他们已经向您解释的那样,事务不能在同一服务内启动。因此,如果您想使第一个方法具有事务性,则必须从您的服务外部调用。