SpringMvc+Mybatis多数据源切换

来源:互联网 发布:唯一网络被收购 编辑:程序博客网 时间:2024/06/04 19:39

昨天经理让我写一个Springmvc连接多数据库的demo。第一次接触这个问题,所以就去网上找了相关资料。发现并不是很难实现,于是在自己之前写的一个登录注册demo上加上这个连接多数据源的部分做测试。我的实现目标是,在登录时查询数据库A,登录成功跳转到下一个页面,而这个页面上显示的数据库是从数据库B拿的。
下面是代码部分:
首先在spring-mybatis.xml配置文件中配置第二个数据库
dataSourceA是原先配置好的第一个数据库。dataSourceB是现在添加的数据库,也是MySql,当然也可以是其他数据库。
这里写图片描述



接下来是配置切换数据源,这里默认的数据库是dataSourceA
这里写图片描述

我这里的两个数据库用的都是MySQL,一个是同事的,一个是本地的。如果是两个不同的数据库,改一下配置条件即可。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:context="http://www.springframework.org/schema/context"     xmlns:jdbc="http://www.springframework.org/schema/jdbc"      xmlns:jee="http://www.springframework.org/schema/jee"     xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:aop="http://www.springframework.org/schema/aop"     xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:util="http://www.springframework.org/schema/util"    xmlns:jpa="http://www.springframework.org/schema/data/jpa"    xsi:schemaLocation="        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">    <!-- 配置MyBatis -->    <bean id="dataSourceA"        class="com.mchange.v2.c3p0.ComboPooledDataSource">        <property name="driverClass"            value="com.mysql.jdbc.Driver"/>        <property name="jdbcUrl"            value="jdbc:mysql://192.168.1.39:3306/doctor-nurse"/>        <property name="user"            value="admin"/>        <property name="password"            value="admin"/>    </bean>    <bean id="dataSourceB"          class="com.mchange.v2.c3p0.ComboPooledDataSource">        <property name="driverClass"                  value="com.mysql.jdbc.Driver"/>        <property name="jdbcUrl"                  value="jdbc:mysql://localhost:3306/doctor-nurse"/>        <property name="user"                  value="root"/>        <property name="password"                  value="root"/>    </bean>    <bean id="dataSource" class="com.lonbon.hispitalcare.datasource.DynamicDataSource">        <property name="targetDataSources">            <map key-type="java.lang.String">                <entry value-ref="dataSourceA" key="dataSourceA"></entry>                <entry value-ref="dataSourceB" key="dataSourceB"></entry>            </map>        </property>        <property name="defaultTargetDataSource" ref="dataSourceA"></property>    </bean>    <!-- 配置SplSessionFactoryBean -->    <bean id="sqlSessionFactory"        class="org.mybatis.spring.SqlSessionFactoryBean">        <property name="dataSource"            ref="dataSource"/>        <!-- mapper文件存储在             src/main/resources/mappers 文件夹 -->        <property name="mapperLocations"            value="classpath:mappers/*.xml"/>    </bean>    <bean id="mapperScanner"         class="org.mybatis.spring.mapper.MapperScannerConfigurer">        <property name="sqlSessionFactory"            ref="sqlSessionFactory"/>        <property name="basePackage"            value="com.lonbon.hispitalcare.dao"/>    </bean>    <!-- 配置视图解析器 -->    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="/WEB-INF/"/>        <property name="suffix" value=".jsp"/>    </bean>    <bean id="transactionManager"          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="dataSource" ref="dataSource" />    </bean></beans>

然后写一个切换数据源的类DynamicDataSource,继承AbstractRoutingDataSource
代码如下:

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;import java.sql.SQLFeatureNotSupportedException;import java.util.logging.Logger;/** * Created by LB on 2017/6/14. * 配置多数据源 */public class DynamicDataSource extends AbstractRoutingDataSource {    public static final String DATASOURCE_A = "dataSourceA";    public static final String DATASOURCE_B = "dataSourceB";    //本地线程,获取当前正在执行的currentThread    public static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();    public static void setCustomerType(String customerType) {        //把当前请求的参数,存入当前线程,这个参数是我们定义的DATASOURCE_A或者DATASOURCE_B        System.out.println("当前切换的数据源="+customerType);        contextHolder.set(customerType);    }    public static String getCustomerType() {        return contextHolder.get();    }    public static void clearCustomerType() {        contextHolder.remove();    }    protected Object determineCurrentLookupKey() {        return getCustomerType();    }    public Logger getParentLogger() throws SQLFeatureNotSupportedException {        return null;    }}

在哪里需要切换数据源,那就在哪个controller里添加
DynamicDataSource.setCustomerType(DynamicDataSource.DATASOURCE_A);即可
这里写图片描述

这样就实现了切换数据源的功能

原创粉丝点击