Mybatis multiple data source calls

Environment: intellij15 , jdk1.8 , maven3

 

Reference: http://www.jb51.net/article/104053.htm

 

1.   Generate ssm project, see http://liguanshi.iteye.com/blog/2413023

2. Add a database connection   in the jdbc.properties file

 

 

#============================================================================
# postgresql
#============================================================================
jdbc.postgresql.driver = org.postgresql.Driver
jdbc.postgresql.url = jdbc:postgresql://127.0.0.1:5432/cz?characterEncoding=UTF-8
jdbc.postgresql.username = postgres
jdbc.postgresql.password = ******

#============================================================================
# oracle
#============================================================================
jdbc.oracle.driver=oracle.jdbc.driver.OracleDriver
jdbc.oracle.url=jdbc:oracle:thin:@smart-dafeng:1521:orcl
jdbc.oracle.username=df
jdbc.oracle.password=******

 

 

3.  Add database connection and multipleDataSource beans in applicationContext - dao.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:aop="http://www.springframework.org/schema/aop"
       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/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--Get database configuration file-->
    <context:property-placeholder location="classpath:config/jdbc.properties"/>
    <!--Set data source c3p0-->
    <bean id="oracleDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="${jdbc.oracle.driver}"/>
        <property name="jdbcUrl" value="${jdbc.oracle.url}"/>
        <property name="user" value="${jdbc.oracle.username}"/>
        <property name="password" value="${jdbc.oracle.password}"/>
        <property name="maxPoolSize" value="50"/>
        <property name="minPoolSize" value="2"/>
        <property name="maxIdleTime" value="60"/>
    </bean>

    <!--Set data source c3p0-->
    <bean id="postgresqlDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="${jdbc.postgresql.driver}"/>
        <property name="jdbcUrl" value="${jdbc.postgresql.url}"/>
        <property name="user" value="${jdbc.postgresql.username}"/>
        <property name="password" value="${jdbc.postgresql.password}"/>
        <property name="maxPoolSize" value="50"/>
        <property name="minPoolSize" value="2"/>
        <property name="maxIdleTime" value="60"/>
    </bean>
    <bean id="multipleDataSource" class="com.elin4it.ssm.utils.MultipleDataSource">
        <property name="defaultTargetDataSource" ref="postgresqlDataSource"/>
        <property name="targetDataSources">
            <map>
                <entry key="postgresqlDataSource" value-ref="postgresqlDataSource"/>
                <entry key="oracleDataSource" value-ref="oracleDataSource"/>
            </map>
        </property>
    </bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="multipleDataSource"/>
    </bean>

    <!-- mybatis.spring auto-mapping -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.elin4it.ssm.mapper"/>
    </bean>

    <!-- Automatic scanning, multiple packages separated by commas -->
    <context:component-scan base-package="com.elin4it.ssm"/>
    <aop:aspectj-autoproxy/>
</beans>

 

 

 

4.  Add the MultipleDataSource class to com.elin4it.ssm.utils

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

/**
 * Created by Administrator on 2018/3/21.
 */
public class MultipleDataSource extends AbstractRoutingDataSource {
    private static final ThreadLocal<String> dataSourceKey = new InheritableThreadLocal<String>();

    public static void setDataSourceKey(String dataSource) {
        dataSourceKey.set(dataSource);
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return dataSourceKey.get();
    }
}

 

 

5. Comment out the content of applicationContext-transaction.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: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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!--<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">-->
        <!--<property name="dataSource" ref="dataSource"/>-->
    <!--</bean>-->

    <!--<tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">-->
        <!--<tx:attributes>-->
            <!--<tx:method name="find*" propagation="REQUIRED"/>-->
            <!--<tx:method name="update*" propagation="REQUIRED"/>-->
            <!--<tx:method name="delete*" propagation="REQUIRED"/>-->
            <!--<tx:method name="add*" propagation="REQUIRED"/>-->
        <!--</tx:attributes>-->
    <!--</tx:advice>-->

    <!--<aop:config>-->
        <!--<aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.elinzhou.ixxs.service.*.*(..))"/>-->
    <!--</aop:config>-->
</beans>

 

 

6.  Add a database selection statement in UserServiceImpl : MultipleDataSource.setDataSourceKey("oracleDataSource");

 

The completion code looks like this:

 

package com.elin4it.ssm.service;

import com.elin4it.ssm.mapper.StudentsMapper;
import com.elin4it.ssm.pojo.Students;
import com.elin4it.ssm.utils.MultipleDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by Administrator on 2018/3/21.
 */
@Service
public class UserServiceImpl implements UserService {
    //User interface needs to add <span style="font-family: Arial, Helvetica, sans-serif;">@Component to dependency injection on UserMapper interface when injecting UserMapper here</span>
    @Autowired
    private StudentsMapper userMapper;
    public Students findUser() throws Exception {
// Switch the database here and output different results
//        MultipleDataSource.setDataSourceKey("postgresqlDataSource");
        MultipleDataSource.setDataSourceKey("oracleDataSource");
        //Call the selectByExample method in the mapper class, if the incoming type is null, it means unconditional search
        Students users = userMapper.selectByPrimaryKey(2);
        return users;
    }
}

 

7.   Add oracle database dependency in pom :

<!-- database driver-->
    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc6</artifactId>
      <version>11.2.0.1.0</version>
</dependency>

 

8.   Run. Oracle database output:

 



After modifying the UserServiceImpl.java code, the Postgresql database outputs the result:

 


 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326111185&siteId=291194637
Recommended