如何在mybatis-spring中使用@Transactional注释?

我尝试在spring使用@Transactional注释,使用mybatis-spring依赖使用mybatis-spring 。 这是服务层。

 @Service public class OracleService { @Autowired private TestMapper mapper; @Autowired private PlatformTransactionManager transactionManager; @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, value = "transactionManager") void insert1() { TestModel testModel = new TestModel(1, "title1", "content1"); mapper.insert(testModel); throw new RuntimeException(); } } 

如您所见,在insert1()抛出了RuntimeException ,因此插入操作应该失败。 但事实上,它没有。 记录已成功插入。 为什么?

这是我的主要方法。

 public class Launcher { public static void main(String[] args) { ApplicationContext cxt = new ClassPathXmlApplicationContext("spring-config.xml"); OracleService oracleService = cxt.getBean(OracleService.class); try { oracleService.insert1(); } catch(Exception e) { System.out.println("Exception occurred!"); } } } 

弹簧配置。

                      

我在pom.xml使用了以下依赖项

   org.mybatis mybatis 3.4.1   org.mybatis mybatis-spring 1.3.0   com.oracle ojdbc6 11.2.0.3   org.springframework spring-jdbc 4.3.2.RELEASE   org.springframework spring-context 4.3.2.RELEASE  

正如@ M.Deinum提到的那样,我必须制作@Transactional公开申请的方法,换句话说,我必须改变

 @Transactional(propagation = Propagation.REQUIRED) void insert1() { TestModel testModel = new TestModel(1, "title1", "content1"); mapper.insert(testModel); throw new RuntimeException(); } 

 @Transactional(propagation = Propagation.REQUIRED) public void insert1() { TestModel testModel = new TestModel(1, "title1", "content1"); mapper.insert(testModel); throw new RuntimeException(); } 

原因写在spring文档中。

方法可见性和@Transactional

使用代理时,您应该仅将@Transactional注释应用于具有公共可见性的方法。 如果使用@Transactional批注对protected,private或package-visible方法进行批注,则不会引发错误,但带注释的方法不会显示已配置的事务设置。 如果需要注释非公共方法,请考虑使用AspectJ(见下文)。