spring+mybatis+springMVC框架配置多数据源

2021-04-18 10:26

阅读:330

标签:tar   thread   ctr   move   切换数据库   ted   xtend   stat   thold   

1.在spring配置文件中配置


    
    bean id="dataSource1" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        property name="driverClass" value="${jdbc.driver}">property>
        property name="jdbcUrl" value="${jdbc.url}">property>
        property name="user" value="${jdbc.username}">property>
        property name="password" value="${jdbc.password}">property>
    bean>
    
    bean id="txManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        
        property name="dataSource" ref="dataSource1">property>
    bean>

    
     
    bean id="dataSource2" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        property name="driverClass" value="${jdbc2.driver}">property>
        property name="jdbcUrl" value="${jdbc2.url}">property>
        property name="user" value="${jdbc2.username}">property>
        property name="password" value="${jdbc2.password}">property>
    bean>
    
    bean id="txManager2"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        
        property name="dataSource" ref="dataSource2">property>
    bean>

    
    bean id="multipleDataSource" class="com.pdzx.util.DynamicDataSource">
        property name="defaultTargetDataSource" ref="dataSource1">property>
        property name="targetDataSources">
            map>
                entry key="dataSource1" value-ref="dataSource1">entry>
                entry key="dataSource2" value-ref="dataSource2">entry>
            map>
        property>
    bean>

2.继承AbstractRoutingDataSource

public class DBContextHolder {

    private static final ThreadLocal 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();
    }

}

 

public class DynamicDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return DBContextHolder.getDbType();
    }
}

3.切换数据库

//指定数据库
DBContextHolder.setDbType("dataSource1");

 

spring+mybatis+springMVC框架配置多数据源

标签:tar   thread   ctr   move   切换数据库   ted   xtend   stat   thold   

原文地址:https://www.cnblogs.com/lusaisai/p/13295560.html


评论


亲,登录后才可以留言!