上一步:教你一步步搭建ssm框架,第二步集成mybatis实现数据的保存
首先查看当前mysql的存储引擎,ENGINE=InnoDB 才支持事务
在上次2篇文章中,我们实现了页面的跳转,数据的保存,本篇文章介绍数据保存事务的控制
首先,我们搭建的框架spring 和 mvc是分开扫描的,分了2个文件
- spring_context.xml
- spring_mvc_context.xml
spring_context.xml是加载配置产生父容器,spring_mvc_context.xml是加载配置子容器。
在子容器中的指定Sping组件扫描的基本包路径中要注意排除对非controller的扫描,以保证事务的增强处理,否则会事务事务处理能力失效,
//可以配置至扫描com.faceghost.app.contorller下的包类
<context:component-scan base-package="com.faceghost.app.contorller">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
或者将@Service注解排除掉
<context:component-scan base-package="com.faceghost.app">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>
事务的拦截应该统一在service层,特别注意,在该层中不要捕获任何异常,全部向外抛,这样事务才能回滚
//这样回滚
public Test getBean(Test bean) throws Except~~~~ion{
testMapper.insert(bean);
System.err.println(1/0);
return bean;
}
//这样不回滚
public Test saveBean(Test bean) throws Exception {
testMapper.insert(bean);
try {
System.err.println(1 / 0);
} catch (Exception e1) {
e1.printStackTrace();
}
return bean;
}
//回滚
public Test saveBean(Test bean) throws Exception {
testMapper.insert(bean);
try {
System.err.println(1 / 0);
} catch (Exception e1) {
throw new Exception(e1);
}
return bean;
}