springMVC mybatis 多数据源配置

1.ssm(spring+springMVC+mybatis)环境搭建(略)

2.工程目录及多数据源涉及的文件


1).DataSourceContextHolder.java

package com.zjgt.datasource;

import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

public class DataSourceContextHolder {
	private static final ThreadLocal<String> contextHolder =new ThreadLocal<>();
	 public static void setDbType(String dbType){
		 contextHolder.set(dbType);
	 }
	 
	 public static String getDbType(){
		 return ((String)contextHolder.get());
	 }
	 public static void clearDbType(){
		 contextHolder.remove();
	 }

}
2).DynamicDataSource.java

package com.zjgt.datasource;

import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource {


	@Override
	protected Object determineCurrentLookupKey() {
		return DataSourceContextHolder.getDbType();
	}

}
3).jdbc.properties

db1.driverClassName=com.mysql.jdbc.Driver
db1.url=jdbc:mysql://localhost:3306/zjzb_qc?useUnicode=true&amp;characterEncoding=UTF-8
db1.username=root
db1.password=123456

db2.driverClassName=com.mysql.jdbc.Driver
db2.url=jdbc:mysql://localhost:3306/zjzb_qc2?useUnicode=true&amp;characterEncoding=UTF-8
db2.username=root
db2.password=123456

db3.driverClassName=com.mysql.jdbc.Driver
db3.url=jdbc:mysql://localhost:3306/zjzb_qc3?useUnicode=true&amp;characterEncoding=UTF-8
db3.username=root
db3.password=123456
4).spring-mybatis.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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans    
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
                        http://www.springframework.org/schema/aop
                        http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
                        ">
	<!-- 自动扫描 -->
	<context:component-scan base-package="com.zjgt.service" />
	<!-- 引入配置文件 -->
	<!-- <bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:jdbc.properties" />
	</bean> -->
 	<bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
                <value>classpath:redis.properties</value>
            </list>
        </property>
    </bean>

<!-- 
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		destroy-method="close">
		<property name="driverClass" value="${jdbc.driverClassName}" />
		<property name="jdbcUrl" value="${jdbc.url}" />
		<property name="user" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="minPoolSize" value="10" />
		<property name="maxPoolSize" value="100" />
		<property name="maxIdleTime" value="1800" />
		<property name="acquireIncrement" value="3" />
		<property name="maxStatements" value="1000" />
		<property name="initialPoolSize" value="10" />
		<property name="idleConnectionTestPeriod" value="60" />
		<property name="acquireRetryAttempts" value="30" />
		<property name="breakAfterAcquireFailure" value="true" />
		<property name="testConnectionOnCheckout" value="false" />
	</bean>
 -->
 
  <!-- 多数据源配置 -->  
   <bean id ="zjzb_qc1" class= "org.apache.commons.dbcp.BasicDataSource" >  
          <property name ="driverClassName" value= "${db1.driverClassName}"></property >  
          <property name ="url" value="${db1.url}"></property>  
          <property name ="username" value="${db1.username}"></property>  
          <property name ="password" value="${db1.password}"></property>  
   </bean >  
   <bean id ="zjzb_qc2" class= "org.apache.commons.dbcp.BasicDataSource" >  
          <property name ="driverClassName" value= "${db2.driverClassName}"></property >  
          <property name ="url" value="${db2.url}"></property>  
          <property name ="username" value="${db2.username}"></property>  
          <property name ="password" value="${db2.password}"></property>  
   </bean >  
   <bean id ="zjzb_qc3" class="org.apache.commons.dbcp.BasicDataSource">  
          <property name ="driverClassName" value= "${db3.driverClassName}"></property >  
          <property name ="url" value="${db3.url}"></property>  
          <property name ="username" value="${db3.username}"></property>  
          <property name ="password" value="${db3.password}"></property>  
   </bean >  
   
   
   
   	<bean id="dataSource" class="com.zjgt.datasource.DynamicDataSource">
		 <property name ="targetDataSources">  
                <map key-type ="java.lang.String">  
                      <entry value-ref ="zjzb_qc1" key="zjzb_qc1"></entry>  
                      <entry value-ref ="zjzb_qc2" key="zjzb_qc2"></entry>  
                      <entry value-ref ="zjzb_qc3" key="zjzb_qc3"></entry>  
                </map >  
          </property >  
          <property name ="defaultTargetDataSource" ref= "zjzb_qc1"></property >      <!-- 默认使用zjzb_qc1的数据源 -->  
	</bean>
 

	<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- 自动扫描mapping.xml文件 -->
		<property name="mapperLocations" value="classpath:com/zjgt/mapping/*.xml"></property>
	</bean>

	<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.zjgt.dao" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>

	<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	
	

	<!-- 配置事务通知属性 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<!-- 定义事务传播属性 -->
		<tx:attributes>
			<tx:method name="insert*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="edit*" propagation="REQUIRED" />
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="new*" propagation="REQUIRED" />
			<tx:method name="set*" propagation="REQUIRED" />
			<tx:method name="remove*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="change*" propagation="REQUIRED" />
			<tx:method name="get*" propagation="REQUIRED" />
			<tx:method name="find*" propagation="REQUIRED" />
			<tx:method name="load*" propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice>

	<!-- 配置事务切面 -->
	<aop:config>
		<aop:pointcut id="txPointcut" expression="execution(* com.zjgt.service.*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
	</aop:config>

</beans>  
3.在web.xml引用spring-mybatis.xml即可

4.在controller里面配置数据源即可(由于service层配置了事务。一旦调用进入到事务内部,再切换数据源则无效。故放在controller里面)

代码示例如下:

@ResponseBody
	@RequestMapping(value = "_list", produces = "text/html;charset=UTF-8")
	public String userLists(HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException {

		//切换数据源到zjzb_qc2
		DataSourceContextHolder.setDbType("zjzb_qc2");
		String userName = request.getParameter("userName");
		String departmentName = request.getParameter("departmentName");
		String pageSize = request.getParameter("pageSize");
		String pageCurrent = request.getParameter("pageCurrent");
		int size = Integer.parseInt(pageSize);
		int currentPage = Integer.parseInt(pageCurrent);
		int start = size * (currentPage - 1);
		int totalSize = userService.getUserListSize(userName, departmentName);
		ArrayList<User> userList = userService.getUserList(userName, departmentName, start, size);
		if (userList.size() > 0) {
			return ToolUtil.listToJson(userList, size, currentPage, totalSize, "yyyy-MM-dd");
		}
		return null;
	}


已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页