spring mvc + mybatis 连接同一地址的多个数据库

来源:互联网 发布:好喝的洋酒推荐 知乎 编辑:程序博客网 时间:2024/05/02 05:42

1. 修改数据库配置mysql.properties文件

driver=com.mysql.jdbc.Driveroldmysql.url=jdbc:mysql://localhost:3306/spider_changed?tinyInt1isBit=falsenewmysql.url=jdbc:mysql://localhost:3306/db_hbrb_spider_async?tinyInt1isBit=falseusername=rootpassword=root#定义初始连接数  initialSize=0#定义最大连接数  maxActive=20#定义最大空闲  maxIdle=20#定义最小空闲  minIdle=1#定义最长等待时间maxWait=60000 

2. 修改mybatis配置 spring-mybatis.xml文件(dataSourceOld、dataSourceNew、dataSource)

<?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"      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">      <!-- 自动扫描 -->      <context:component-scan base-package="com.spiderweb">    </context:component-scan>    <!-- 引入配置文件 -->      <bean id="propertyConfigurer"          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">          <property name="location" value="classpath:mysql.properties" />      </bean>      <bean id="dataSourceOld" class="org.apache.commons.dbcp.BasicDataSource"          destroy-method="close">          <property name="driverClassName" value="${driver}" />          <property name="url" value="${oldmysql.url}" />          <property name="username" value="${username}" />          <property name="password" value="${password}" />          <!-- 初始化连接大小 -->          <property name="initialSize" value="${initialSize}"></property>          <!-- 连接池最大数量 -->          <property name="maxActive" value="${maxActive}"></property>          <!-- 连接池最大空闲 -->          <property name="maxIdle" value="${maxIdle}"></property>          <!-- 连接池最小空闲 -->          <property name="minIdle" value="${minIdle}"></property>          <!-- 获取连接最大等待时间 -->          <property name="maxWait" value="${maxWait}"></property>      </bean>     <bean id="dataSourceNew" class="org.apache.commons.dbcp.BasicDataSource"          destroy-method="close">          <property name="driverClassName" value="${driver}" />          <property name="url" value="${newmysql.url}" />          <property name="username" value="${username}" />          <property name="password" value="${password}" />          <!-- 初始化连接大小 -->          <property name="initialSize" value="${initialSize}"></property>          <!-- 连接池最大数量 -->          <property name="maxActive" value="${maxActive}"></property>          <!-- 连接池最大空闲 -->          <property name="maxIdle" value="${maxIdle}"></property>          <!-- 连接池最小空闲 -->          <property name="minIdle" value="${minIdle}"></property>          <!-- 获取连接最大等待时间 -->          <property name="maxWait" value="${maxWait}"></property>      </bean>     <bean id="dataSource" class="com.spiderweb.common.DynamicDataSource"><!-- 这里写选择数据源的类地址 下面跟着给出-->        <property name="defaultTargetDataSource" ref="dataSourceOld"/><!-- 设置默认为此dataSourceOld数据源-->        <property name="targetDataSources">            <map>                <entry key="dataSourceOld" value-ref="dataSourceOld"/>                <entry key="dataSourceNew" value-ref="dataSourceNew"/>            </map>        </property>    </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/spiderweb/mapping/*/*.xml"></property>      </bean>      <!-- DAO接口所在包名,Spring会自动查找其下的类 -->      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">          <property name="basePackage" value="com.spiderweb.dao.mapper.*" />          <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>  </beans>  

3. 创建类DbcontextHolder

package com.spiderweb.common;import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;public class DbcontextHolder extends AbstractRoutingDataSource {    public static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();    /**     * 设置当前数据源     * @param dbType     */    public static void setDbType(String dbType){        contextHolder.set(dbType);    }    /**     * 获得当前数据源     * @return     */    public static String getDbType(){        String dbType = (String)contextHolder.get();        return dbType;    }    /**     *清除上下文     *     */    public void clearContext(){        contextHolder.remove();    }    @Override    protected Object determineCurrentLookupKey() {        return DbcontextHolder.getDbType();    }}

4. 在方法中连接不同数据库

//连接dataSourceOld进行查询DbcontextHolder.setDbType("dataSourceOld");Template template = templateMapperExtend.selectByPrimaryKey(templateId);//连接dataSourceNew进行插入DbcontextHolder.setDbType("dataSourceNew");siteAsyncMapper.insertSelective(siteAsync);