spring+mybatis 配置双数据源

Posted 10年 Java程序员,硬核人生!勇往直前,永不退缩!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring+mybatis 配置双数据源相关的知识,希望对你有一定的参考价值。

配置好后,发现网上已经做好的了, 不过,跟我的稍有不同, 我这里再拿出来现个丑:

properties 文件自不必说,关键是这里的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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:cache="http://www.springframework.org/schema/cache" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                        http://www.springframework.org/schema/aop
                        http://www.springframework.org/schema/aop/spring-aop.xsd
                        http://www.springframework.org/schema/cache
                        http://www.springframework.org/schema/cache/spring-cache-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/context
                        http://www.springframework.org/schema/context/spring-context-3.2.xsd
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
                        
    <!-- 属性文件读入 -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:dfintop.properties</value>
            </list>
        </property>
    </bean>
                        
    <!-- 它背后注册了很多用于解析注解的处理器,其中就包括<context:annotation-config/>配置的注解所使用的处理器 -->
    <!-- 所以配置了<context:component-scan base-package="">之后,便无需再配置<context:annotation-config> -->
    <context:component-scan base-package="com.dffk.dfintop.**.controller,com.dffk.dfintop.**.service,com.dffk.dfintop.**.quartz,com.dffk.dfintop.**.shiro,com.dffk.dfintop.common.util,com.dffk.dfintop.common.listener,com.dffk.dfintop.framework.websocket,org.activiti.rest.editor">
    <!-- <context:component-scan base-package="com.dffk.dfintop"> -->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
        <!-- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> -->
    </context:component-scan>
    
    <!-- 启用SpringMVC的注解功能,它会自动注册HandlerMapping、HandlerAdapter、ExceptionResolver的相关实例 -->
    <mvc:annotation-driven/>

    <!-- json处理 -->
    <bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper"></bean>
    
    <!-- 数据源配置, 使用 BoneCP 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
        init-method="init" destroy-method="close">
        <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->
        <property name="driverClassName" value="${jdbc.driver}" />
        <!-- 基本属性 url、user、password -->
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="${jdbc.pool.init}" />
        <property name="minIdle" value="${jdbc.pool.minIdle}" />
        <property name="maxActive" value="${jdbc.pool.maxActive}" />
        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000" />
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <property name="validationQuery" value="${jdbc.testSql}" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用) <property name="poolPreparedStatements" 
            value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" 
            value="20" /> -->
        <!-- 配置监控统计拦截的filters -->
        <property name="filters" value="stat" />
    </bean>

    <!-- 数据源配置, 使用 BoneCP 数据库连接池 -->
    <bean id="dataSource_2" class="com.alibaba.druid.pool.DruidDataSource"
        init-method="init" destroy-method="close">
        <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->
        <property name="driverClassName" value="${jdbc_2.driver}" />
        <!-- 基本属性 url、user、password -->
        <property name="url" value="${jdbc_2.url}" />
        <property name="username" value="${jdbc_2.username}" />
        <property name="password" value="${jdbc_2.password}" />
        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="${jdbc_2.pool.init}" />
        <property name="minIdle" value="${jdbc_2.pool.minIdle}" />
        <property name="maxActive" value="${jdbc_2.pool.maxActive}" />
        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000" />
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <property name="validationQuery" value="${jdbc_2.testSql}" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用) <property name="poolPreparedStatements"
            value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize"
            value="20" /> -->
        <!-- 配置监控统计拦截的filters -->
        <property name="filters" value="stat" />
    </bean>

    <bean id="dataBean" class="com.dffk.dfintop.common.util.DBUtils">  
        <property name="dataSource">  
            <ref bean="dataSource"/>  
        </property>
    </bean>
    <bean id="dataBean_2" class="com.dffk.dfintop.common.util.DBUtils">
        <property name="dataSource">
            <ref bean="dataSource_2"/>
        </property>
    </bean>
    
    <!-- 创建SqlSessionFactory,同时指定数据源==org.mybatis.spring.SqlSessionFactoryBean== -->
    <bean id="sqlSessionFactory" class="com.dffk.dfintop.framework.system.mybatis.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="com.dffk.dfintop" />
        <property name="mapperLocations" value="classpath:mapper/${jdbc.type}/**/*.xml" />
        <property name="configLocation" value="classpath:mybatis-config.xml" />
    </bean>
    <!-- 创建SqlSessionFactory,同时指定数据源==org.mybatis.spring.SqlSessionFactoryBean== -->
    <bean id="sqlSessionFactory_2" class="com.dffk.dfintop.framework.system.mybatis.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource_2" />
        <property name="typeAliasesPackage" value="com.dffk.dfintop" />
        <property name="mapperLocations" value="classpath:mapper/${jdbc_2.type}/**/*.xml" />
        <property name="configLocation" value="classpath:mybatis-config.xml" />
    </bean>
    
    <!-- 配置事务 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置事务 -->
    <bean id="transactionManager_2" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource_2" />
    </bean>

    <!-- 配置 Annotation 驱动,扫描@Transactional注解的类定义事务
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>-->
    <tx:annotation-driven transaction-manager="transactionManager" />
    <tx:annotation-driven transaction-manager="transactionManager_2" />

    <!-- 配置 JSR303 Bean Validator 定义 -->
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
    
    <!-- scan mappers and let them be autowired -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.dffk.dfintop" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- scan mappers and let them be autowired -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.dffk.dfintop_2" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory_2"></property>
    </bean>

    <!-- swagger config -->
    <bean class="com.dffk.dfintop.common.swagger.MySwaggerConfig"/>
    
    <!-- 拦截器配置
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**" />
            <mvc:exclude-mapping path="/act/**"/>
            <mvc:exclude-mapping path="/assets/**"/>
            <mvc:exclude-mapping path="/bootstrap/**"/>
            <mvc:exclude-mapping path="/script/**"/>
            <mvc:exclude-mapping path="/static/**"/>
            <mvc:exclude-mapping path="/swagger/**"/>
            <mvc:exclude-mapping path="/ws/**"/>
            <mvc:exclude-mapping path="/api-docs/**"/>
            <mvc:exclude-mapping path="/ks/chart/**"/>
            <mvc:exclude-mapping path="/upload/**"/>
            <mvc:exclude-mapping path="/portal/**"/>
            <mvc:exclude-mapping path="/login/**"/>
            <mvc:exclude-mapping path="/cms/**"/>
            <mvc:exclude-mapping path="/sys/**"/>
            <mvc:exclude-mapping path="/"/>
            <bean class="com.dffk.dfintop.common.interceptor.AuthorityInterceptor" />
        </mvc:interceptor> -->
        <!-- <mvc:interceptor>
            <mvc:mapping path="/**" />
            <mvc:exclude-mapping path="/assets/**"/>
            <mvc:exclude-mapping path="/bootstrap/**"/>
            <mvc:exclude-mapping path="/script/**"/>
            <mvc:exclude-mapping path="/static/**"/>
            <mvc:exclude-mapping path="/swagger/**"/>
            <mvc:exclude-mapping path="/ws/**"/>
            <mvc:exclude-mapping path="/api-docs/**"/>
            <mvc:exclude-mapping path="/ks/chart/**"/>
            <mvc:exclude-mapping path="/upload/**"/>
            <mvc:exclude-mapping path="/portal/**"/>
            <mvc:exclude-mapping path="/sys/**"/>
            <mvc:exclude-mapping path="/information/**"/>
            <mvc:exclude-mapping path="/"/>
            <bean class="com.dffk.dfintop.common.interceptor.LogInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>-->
</beans>

 

因为,我们使用了 MapperScannerConfigurer ,dao bean是spring 动态生成的,我们可以不用写dao 实现了。 但是我们需要配置 MapperScannerConfigurer ,指向我们需要使用双数据源的 package, 这个package 最好和之前数据源不同, 以示区别 。

同时, 我们需要配置  transaction-manager ,这里的transaction-manager  是一个注解式的事务管理器。

 

dao 是可以不用写了。但是, 接口是必须的,我开始的时候是直接复制了原有的dao 接口, 但是发现有问题就是 dao  的bean 的name 和原有的发生冲突。 怎么办呢, 只有改名了, 我就直接加了个2:

/*
 * Powered By luokai
 * Since 2014 - 2017
 */
package com.dffk.dfintop_2.credit;

import com.dffk.dfintop.bussiness.credit.domain.CustomerInfo;
import com.dffk.dfintop.common.exception.CRUDException;
import com.dffk.dfintop.framework.system.domain.SysUser;

import java.util.List;

/**
 * @author luokai
 * @version 1.0
 * @since 1.0
 */
public interface CustomerInfoMapper2 {

    /**
     * 根据ID查询单条数据
     * @param id
     * @return
     */
    public CustomerInfo findOne(String id);
    
    /**
     * 查询数据集合
     * @param customerInfo
     * @return
     */
    public List<CustomerInfo> findList(CustomerInfo customerInfo);
    
    /**
     * 查询数据TREE
     * @param sysUser
     * @return
     * @throws CRUDException
     */
    public List<CustomerInfo> findTree(SysUser sysUser);
    
    /**
     * 查询数据TREE
     * @param customerInfo
     * @return
     * @throws CRUDException
     */
    public List<CustomerInfo> findAll(CustomerInfo customerInfo);
    
    /**
     * 查询数据总数
     * @param customerInfo
     * @return
     */
    public Integer findTotal(CustomerInfo customerInfo);
    
    /**
     * 数据新增
     * @param customerInfo
     */
    public void save(CustomerInfo customerInfo);
    
    /**
     * 数据修改
     * @param customerInfo
     */
    public void update(CustomerInfo customerInfo);
    
    /**
     * 数据删除
     * @param listId
     */
    public void delete(List<String> listId);
}

 

然后就是使用了, 使用很简单, 通过@Autowired 注解就行了:

@Service
public class XxxService extends BaseService {

    @Autowired
    private CustomerInfoMapper customerInfoMapper;

    @Autowired
    private ContractInfoMapper contractInfoMapper;

    @Autowired
    private ImageInfoMapper imageInfoMapper;

    @Autowired
    private BusinessIntoMapper businessIntoMapper;


    @Autowired
    private com.dffk.dfintop_2.credit.CustomerInfoMapper2 customerInfoMapper2;

    @Autowired
    private com.dffk.dfintop_2.credit.ContractInfoMapper2 contractInfoMapper2;

    @Autowired
    private com.dffk.dfintop_2.credit.ImageInfoMapper2 imageInfoMapper2;

    @Autowired
    private com.dffk.dfintop_2.credit.BusinessIntoMapper2 businessIntoMapper2;

...


}


// 注,
BaseService 使用了 @Transactional 注解,也就是注解方式启用了事务管理器。
@Transactional(readOnly = false)
public abstract class BaseService {

}
 

 

参考:

http://www.cnblogs.com/zyzcj/p/6653549.html

http://www.cnblogs.com/liujiduo/p/5004691.html

以上是关于spring+mybatis 配置双数据源的主要内容,如果未能解决你的问题,请参考以下文章

MyBatis Spring SqlSessionFactoryBean 配置

MyBatis Spring MapperScannerConfigurer 配置

请教mybatis+spring+atomikos的整合问题

Mybatis与Spring整合后的配置与使用

MyBatis简介与配置MyBatis+Spring+MySql

spring boot mybatis 读取配置文件