您的位置:首页 > 编程语言 > Java开发

mybatis + springMVC 多数据源,及事务配置

2016-09-30 13:14 661 查看
之前写过一种多数据源配置的方式,但是那种方式对代码入侵性比较大,详情请查阅

mybatis + spring 多数据源跨库查询

最近在做 springMVC 搭建时,更改了新的实现,并且提供多数据源中单个数据源事务的支持

下面直接放完整代码:

web.xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>testweb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

<!-- webAppRootKey -->
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>mvnweb.root</param-value>
</context-param>

<!-- ========== Log4j 监听器 ========== -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:config/log4j/log4j.xml</param-value>
</context-param>

<!-- spring mvc -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring/springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<!-- ========== spring 配置文件 ========== -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:config/spring/applicationContext.xml
</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- ========== session 超时 ========== -->
<session-config>
<session-timeout>60</session-timeout>
</session-config>

<error-page>
<error-code>404</error-code>
<location>/page/common/error/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/page/common/error/500.jsp</location>
</error-page>
</web-app>

springmvc-servlet.xml 配置文件

<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 
<!-- 注册HandlerMapper、HandlerAdapter两个映射类 -->
<mvc:annotation-driven />
<context:component-scan base-package="com.ysq.mvnweb.*"
use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>

<!-- 访问静态资源 -->
<mvc:default-servlet-handler />

<!-- 视图解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/page/"></property>
<property name="suffix" value=".jsp"></property>
</bean>

</beans>

applicationContext.xml 配置

<?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-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> 
<!-- 读取数据源配置文件 -->
<bean id="dataSoucresConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations"
value="classpath:config/properties/dbConfig.properties" />
</bean>

<!-- 使用annotation自动注册bean,并保证@Required,@Autowired的属性被注入 -->
<context:annotation-config />
<context:component-scan base-package="com.ysq.mvnweb.*">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>

<!-- 自动AOP切面 -->
<aop:aspectj-autoproxy />

<bean id="baseDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driverClass}"/>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="${jdbc.acquireIncrement}"/>
<!--初始化时获取连接个数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="${jdbc.initialPoolSize}"/>
<!--最大空闲时间內未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime" value="${jdbc.maxIdleTime}"/>
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"/>
<!--连接池中保留的最小连接数。-->
<property name="minPoolSize" value="${jdbc.minPoolSize}"/>

<!--两次连接中间隔时间,单位毫秒。Default: 1000 -->
<property name="acquireRetryDelay" value="${jdbc.acquireRetryDelay}"/>
<!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
<property name="acquireRetryAttempts" value="${jdbc.acquireRetryAttempts}"/>
<!-- 为 true 时 pool向数据库请求连接失败后标记整个pool为block并close -->
<property name="breakAfterAcquireFailure" value="${jdbc.breakAfterAcquireFailure}"/>
</bean>

<!-- ========== 数据源一:mvc DBSource ========== -->
<bean id="mvcDBSource" parent="baseDataSource">
<property name="jdbcUrl" value="${jdbc.dbUrl}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}" />
</bean>

<bean id="mvcSqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="mvcDBSource" />
<property name="configLocation" value="classpath:config/mybatis/Configuration.xml" />
<property name="mapperLocations">
<list>
<value>classpath*:config/mybatis/sqlMapper/common/*.xml</value>
<value>classpath*:config/mybatis/sqlMapper/webview/*.xml</value>
<value>classpath*:config/mybatis/sqlMapper/setting/*.xml</value>
<value>classpath*:config/mybatis/sqlMapper/open/*.xml</value>
</list>
</property>
</bean>

<!-- 事务 -->
<bean id="transationManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="mvcDBSource" />
<qualifier value="mvcTran"/>
</bean>
<tx:annotation-driven transaction-manager="transationManager" />

<!-- ========== 数据源二:mvc DBSource ========== -->
<bean id="testDBSource" parent="baseDataSource">
<property name="jdbcUrl" value="${jdbc.testdbUrl}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}" />
</bean>

<bean id="testSqlSession" parent="mvcSqlSession">
<property name="dataSource" ref="testDBSource" />
</bean>

<!-- 事务 -->
<bean id="testTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="testDBSource" />
<qualifier value="testTran"/>
</bean>
<tx:annotation-driven transaction-manager="testTransactionManager" />

</beans>


注意:applicationContext.xml 与 springmvc-servlet.xml 中 <context:component-scan> 的配置,两者需要扫描的注解不同,如果有冲突,就会导致 事务注解不生效。

dao 实现类

baseDao

public class BaseDaoSupportImpl extends SqlSessionDaoSupport implements IBaseDaoSupport {

/**
* mybatis-spring-1.2.x.jar 版本的 sqlSessionTemplate 注入有所改动,必须重写次方法
*/
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
super.setSqlSessionFactory(sqlSessionFactory);
}

protected <S> S getMapper(Class<S> clazz) {
return getSqlSession().getMapper(clazz);
}

}


数据源一

/**
* 多数据源之 mvc dao
* @author Administrator
*
*/
@Repository("mvcDaoSupport")
public class MvcDaoSupportImpl extends BaseDaoSupportImpl implements IMvcDaoSupport {

@Resource(name="mvcSqlSession")
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
super.setSqlSessionFactory(sqlSessionFactory);
}

}

数据源二

/**
* 多数据源之 mvc dao
* @author Administrator
*
*/
@Repository("testDaoSupport")
public class TestDaoSupportImpl extends BaseDaoSupportImpl implements ITestDaoSupport {

@Resource(name="testSqlSession")
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
super.setSqlSessionFactory(sqlSessionFactory);
}

}

使用方法,所有service 继承自 baseService

public class BaseServiceSupportImpl implements IBaseServiceSupport {
protected Logger logger = CommonUtil.getLogger(this.getClass());

@Resource(name = "mvcDaoSupport")
protected IBaseDaoSupport mvcDao;

@Resource(name = "testDaoSupport")
protected IBaseDaoSupport testDao;

}


测试事务类

/**
* 事务保存测试
*/
@Transactional("testTran")
public void saveMore() throws Exception{

mvcDao.save(mapperName + "mvcInsert", null);

testDao.save(mapperName + "testInsert", null);

List<String> testList = new ArrayList<String>();

System.out.println(testList.get(3));

}


注意,同一时间内,只能保证一个数据源的事务
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息