1.在Mysql中,只有当表的类型是INNODB的时候,才支持事务,所以需要把表的类型设置为INNODB,否则无法观察到事务.
修改表的类型为INNODB的SQL:
alter table hero ENGINE = innodb;
查看表的类型的SQL
show table status from tablename;
2.
applicationContext.xml
<!-- 开启事务注解,标注@Transactional的类和方法将具有事务性 --> <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true" /> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean>
<!--spring的配置文件application.xml中包扫描不需要扫描@Controller注解的, 具体如下:--> <context:component-scan base-package="com.crossoverJie"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/> </context:component-scan>
3.SpringMVC.xml
<!--springMVC配置文件springMVC-servlet.xml中只需要扫描@Controller注解的,具体如下:--> <context:component-scan base-package="com.crossoverJie"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> <!--下面这个是防止事务没起作用,spring.xml的父容器先于Servlet的子容器生效,将Service提前加载了。这里不用再进行加载装配--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan>
4.test
在方法上加上注解:
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class) @Override public void addTwo() { addOne(); Category c1 = new Category(); c1.setName("短的名字"); categoryMapper.add(c1); } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class) @Override public void addOne() { Category c2 = new Category(); c2.setName("名字长对应字段放不下"); categoryMapper.add(c2); int i = 9 / 0; //这里会抛出异常 }
执行并查看日志:
java.lang.NullPointerException //异常信息
DEBUG [main] (AbstractPlatformTransactionManager.java:847) - Initiating transaction rollback //回滚
DEBUG [main] (DataSourceTransactionManager.java:284) - Rolling back JDBC transaction on Connection [com.mysql.jdbc.JDBC4Connection@6ea2bc93]
DEBUG [main] (DataSourceTransactionManager.java:327) - Releasing JDBC Connection [com.mysql.jdbc.JDBC4Connection@6ea2bc93] after transaction
DEBUG [main] (DataSourceUtils.java:327) - Returning JDBC Connection to DataSource //返回连接到连接池
说明事务生效了,遇到异常回滚。