前言:近期换了新公司,刚来公司就接触了一下mybatis,因为springmvc和spring比较熟悉,我想大概现在绝大部分的公司都在用吧,刚接触mybatis时感觉真心蛋疼,纯sql才处理业务,实在是有点不习惯,不过感觉整个框架较之前的orm架构确实感觉速度快一点。
好了,直接进入正题
需求:需要在一个业务层方法内完成对两张不同的表进行插入操作
一开始我直接在mybatis的配置文件中想写两条sql语句,两条sql语句已“;”隔开,不过没成功,网上查了一下资料说mybatis不支持这样的,这条路行不通之后显然就只剩下另外一条路了:在业务层的某个方法中调用两次dao的,对两张不同的表进行插入操作。
此方式可行:
public void method(Param param) throws Exception {
dao.save("xxx.save", param);
dao.save("yyy.save", param);
}
但是如果这种方式需要考虑事务问题,于是在两个方法之间抛出一个异常准备试一试事务机制
public void method(Param param) throws Exception {
dao.save("xxx.save", param);
int a = 1/0;
dao.save("yyy.save", param);
}
不试不知道,一试了一下,果然没有进行回滚
以下是dao的代码:
@Repository("daoSupport")
public class DaoSupport implements Dao {
@Resource(name = "sqlSessionTemplate")
private SqlSessionTemplate sqlSessionTemplate;
public Object save(String str, Object obj) throws Exception {
return sqlSessionTemplate.insert(str, obj);
}
}
spring配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
">
<!-- 启用注解 -->
<context:annotation-config />
<!-- 启动组件扫描,排除@Controller组件,该组件由SpringMVC配置文件扫描 -->
<context:component-scan base-package="com.???">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/classes/dbconfig.properties</value>
</list>
</property>
</bean>
<!-- 阿里 druid数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<!-- 数据库基本信息配置 -->
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<property name="driverClassName" value="${driverClassName}" />
<property name="filters" value="${filters}" />
<!-- 最大并发连接数 -->
<property name="maxActive" value="${maxActive}" />
<!-- 初始化连接数量 -->
<property name="initialSize" value="${initialSize}" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="${maxWait}" />
<!-- 最小空闲连接数 -->
<property name="minIdle" value="${minIdle}" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
<property name="validationQuery" value="${validationQuery}" />
<property name="testWhileIdle" value="${testWhileIdle}" />
<property name="testOnBorrow" value="${testOnBorrow}" />
<property name="testOnReturn" value="${testOnReturn}" />
<property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements}" />
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="${removeAbandoned}" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="${logAbandoned}" />
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="delete*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception"/>
<tx:method name="insert*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="update*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="save*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
</tx:attributes>
</tx:advice>
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!-- 事物处理 -->
<aop:config>
<aop:pointcut id="pc" expression="execution(* xxx..*(..))" />
<aop:advisor pointcut-ref="pc" advice-ref="txAdvice" />
</aop:config>
<!-- 配置mybatis -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
<!-- mapper扫描 -->
<property name="mapperLocations" value="classpath:mybatis/*/*.xml"></property>
</bean>
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory" />
</bean>
<!-- ================ Shiro start ================ -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="ShiroRealm" />
</bean>
<!-- 項目自定义的Realm -->
<bean id="ShiroRealm" class="com.???.basic.interceptor.shiro.ShiroRealm" ></bean>
<!-- Shiro Filter -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="/" />
<property name="successUrl" value="/main/index" />
<property name="unauthorizedUrl" value="/login_toLogin" />
<property name="filterChainDefinitions">
<value>
/wap/**/** = anon
/static/login/** = anon
/static/js/myjs/** = authc
/static/js/** = anon
/static/wap/** = anon
/code.do = anon
/login_login = anon
/app**/** = anon
/weixin/** = anon
/** = authc
</value>
</property>
</bean>
</beans>
springmvc配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<context:component-scan base-package="com.xxx" />
<!-- 对静态资源文件的访问 restful-->
<mvc:resources mapping="/admin/**" location="/,/admin/" />
<mvc:resources mapping="/static/**" location="/,/static/" />
<mvc:resources mapping="/plugins/**" location="/,/plugins/" />
<mvc:resources mapping="/uploadFiles/**" location="/,/uploadFiles/" />
<!-- 访问拦截 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**/**"/>
<bean class="com.xxx.basic.interceptor.LoginHandlerInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
<!-- 配置SpringMVC的视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="exceptionResolver" class="com.???.basic.resolver.MyExceptionResolver"></bean>
<!-- 上传拦截,如最大上传值及最小上传值 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
<property name="defaultEncoding">
<value>utf-8</value>
</property>
</bean>
</beans>
后来在网上看到了这个,试了以下,果然解决了点击打开链接
解决方案:修改springmvc配置文件,
修改内容:
<!-- 启动组件扫描,排除@Service组件,注:如果此处必须排除掉@Service组件
原因:springmvc的配置文件与spring的配置文件不是同时加载,如果这边不进行这样的设置,
那么,spring就会将所有带@Service注解的类都扫描到容器中,
等到加载spring的配置文件的时候,会因为容器已经存在Service类,
使得cglib将不对Service进行代理,直接导致的结果就是在spring配置文件中的事务配置不起作用,发生异常时,无法对数据进行回滚
-->
<context:component-scan base-package="com.???">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Service" />
</context:component-scan>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<strong><span style="color:#ff0000;"><!-- 启动组件扫描,排除@Service组件,注:如果此处必须排除掉@Service组件
原因:springmvc的配置文件与spring的配置文件不是同时加载,如果这边不进行这样的设置,
那么,spring就会将所有带@Service注解的类都扫描到容器中,
等到加载spring的配置文件的时候,会因为容器已经存在Service类,
使得cglib将不对Service进行代理,直接导致的结果就是在spring配置文件中的事务配置不起作用,发生异常时,无法对数据进行回滚
--></span></strong>
<context:component-scan base-package="com.xxx">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Service" />
</context:component-scan></strong></span>
<!-- 对静态资源文件的访问 restful-->
<mvc:resources mapping="/admin/**" location="/,/admin/" />
<mvc:resources mapping="/static/**" location="/,/static/" />
<mvc:resources mapping="/plugins/**" location="/,/plugins/" />
<mvc:resources mapping="/uploadFiles/**" location="/,/uploadFiles/" />
<!-- 访问拦截 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**/**"/>
<bean class="com.xxx.basic.interceptor.LoginHandlerInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
<!-- 配置SpringMVC的视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="exceptionResolver" class="com.???.basic.resolver.MyExceptionResolver"></bean>
<!-- 上传拦截,如最大上传值及最小上传值 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
<property name="defaultEncoding">
<value>utf-8</value>
</property>
</bean>
</beans>
修改后重启tomcat后就有事务了!!!!,感恩 感恩!~~~
总结:如果spring和springmvc整合的时候,两个配置文件各自扫描自己的类,mvc配置文件就扫描controller,不扫描其他的,而spring配置文件件不扫描controller,扫描其他的。
备注:我之前一个项目是将事务的配置配置在springmvc的配置文件当中,两个配置文件都扫描全部,所以不会有问题