1. 程式人生 > >MyBatis 配置多資料來源

MyBatis 配置多資料來源


<?
xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
> <!--資料來源2 --> <bean id="projectdataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password"
value="${jdbc.password}" /> <property name="initialSize" value="${jdbc.initialSize}" /> <property name="minIdle" value="${jdbc.minIdle}" /> <property name="maxActive" value="${jdbc.maxIdle}" /> <property name="maxWait" value="${jdbc.maxActive}" /> <property
name="timeBetweenEvictionRunsMillis" value="60000" /> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value="SELECT 'x'" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="poolPreparedStatements" value="false" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> <property name="connectionProperties" value="useUnicode=true;characterEncoding=utf8;connectTimeout=5000;socketTimeout=60000;autoReconnect=true;failOverReadOnly=false;allowMultiQueries=true" /> </bean>

<bean id="projectsqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation"> <value>classpath:mybatis/mapper1.xml</value> </property> <property name="dataSource" ref="projectdataSource" /> </bean> <bean id="projectsqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="projectsqlSessionFactory" /> </bean> <!--資料來源3 UC 資料 --> <bean id="ucDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.uc.url}" /> <property name="username" value="${jdbc.uc.username}" /> <property name="password" value="${jdbc.uc.password}" /> <property name="initialSize" value="${jdbc.uc.initialSize}" /> <property name="minIdle" value="${jdbc.uc.minIdle}" /> <property name="maxActive" value="${jdbc.uc.maxIdle}" /> <property name="maxWait" value="${jdbc.uc.maxActive}" /> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value="SELECT 'x'" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="poolPreparedStatements" value="false" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> <property name="connectionProperties" value="useUnicode=true;characterEncoding=utf8;connectTimeout=5000;socketTimeout=60000;autoReconnect=true;failOverReadOnly=false;allowMultiQueries=true" /> </bean> <bean id="ucSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation"> <value>classpath:mybatis/mapper_uc.xml</value> </property> <property name="dataSource" ref="ucDataSource" /> </bean> <bean id="ucSqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="ucSqlSessionFactory" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.qdingnet.pcloud.adverts.uc.ucext" /> <property name="sqlSessionTemplateBeanName" value="ucSqlSession" /> </bean> <!--資料來源1 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${ad.db.url}" /> <property name="username" value="${ad.db.username}" /> <property name="password" value="${ad.db.password}" /> <property name="initialSize" value="${ad.db.initialSize}" /> <property name="minIdle" value="${ad.db.minIdle}" /> <property name="maxActive" value="${ad.db.maxActive}" /> <property name="maxWait" value="${ad.db.maxWait}" /> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value="SELECT 'x'" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="poolPreparedStatements" value="false" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> <property name="connectionProperties" value="useUnicode=true;characterEncoding=utf8;connectTimeout=5000;socketTimeout=60000;autoReconnect=true;failOverReadOnly=false;allowMultiQueries=true" /> </bean> <!--mybatis --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation"> <value>classpath:mybatis/mapper.xml</value> </property> <property name="dataSource" ref="dataSource" /> </bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> </bean> <aop:aspectj-autoproxy /> <!-- 註解Mapper scanner --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.xihl.region.chargeext" /> <property name="sqlSessionTemplateBeanName" value="projectsqlSession" /> </bean> <!--事務 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.xihl.**.ext" /> <property name="sqlSessionTemplateBeanName" value="sqlSession" /> </bean> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="txManager" /> </beans>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!-- 將下劃線欄位名稱對映為駝峰變數  -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- 進位制mybatis進行延遲載入 -->
        <setting name="lazyLoadingEnabled" value="false"/>
        <setting name="useGeneratedKeys" value="true" />
    </settings>
    <!-- 外掛配置 -->
    <plugins>
        <!-- com.github.pagehelper為PageHelper類所在包名 -->
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
           <!-- <property name="dialect" value="mysql"/>-->
            <!-- 該引數預設為false -->
            <!-- 設定為true時,會將RowBounds第一個引數offset當成pageNum頁碼使用 -->
            <!-- 和startPage中的pageNum效果一樣-->
            <property name="offsetAsPageNum" value="false"/>
            <!-- 該引數預設為false -->
            <!-- 設定為true時,使用RowBounds分頁會進行count查詢 -->
            <property name="rowBoundsWithCount" value="false"/>
            <!-- 設定為true時,如果pageSize=0或者RowBounds.limit = 0就會查詢出全部的結果 -->
            <!-- (相當於沒有執行分頁查詢,但是返回結果仍然是Page型別)-->
            <property name="pageSizeZero" value="false"/>
            <!-- 3.3.0版本可用 - 分頁引數合理化,預設false禁用 -->
            <!-- 啟用合理化時,如果pageNum<1會查詢第一頁,如果pageNum>pages會查詢最後一頁 -->
            <!-- 禁用合理化時,如果pageNum<1或pageNum>pages會返回空資料 -->
            <property name="reasonable" value="false"/>
            <!-- 3.5.0版本可用 - 為了支援startPage(Object params)方法 -->
            <!-- 增加了一個`params`引數來配置引數對映,用於從Map或ServletRequest中取值 -->
            <!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,orderBy,不配置對映的用預設值 -->
            <!-- 不理解該含義的前提下,不要隨便複製該配置 -->
            <property name="params" value="pageNum=pageNum;pageSize=pageSize;"/>
            <!-- 支援通過Mapper介面引數來傳遞分頁引數 -->
            <property name="supportMethodsArguments" value="false"/>
            <!-- always總是返回PageInfo型別,check檢查返回型別是否為PageInfo,none返回Page -->
            <property name="returnPageInfo" value="check"/>
        </plugin>
        <plugin interceptor="com.xhl.log.plugins.SqlLogger">
            <!-- 設定超過多長時間就列印這條sql,單位為ms。預設為600ms。  -->
            <property name="exccedtime" value="1500"/>
        </plugin>
    </plugins>
    <mappers>
        <mapper resource="mybatis/mapper_uc_user_detail.xml"></mapper> <!-- 這裡引入的真是真正的MyBatis配置檔案-->
    </mappers>
</configuration>
import java.text.DateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Intercepts({@Signature(
    type = Executor.class,
    method = "update",
    args = {MappedStatement.class, Object.class}
), @Signature(
    type = Executor.class,
    method = "query",
    args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
)})
public class SqlLogger implements Interceptor {
    private final Logger _LOGGER = LoggerFactory.getLogger(this.getClass());
    private static Long exceedTime = 600L;

    public SqlLogger() {
    }

    public Object intercept(Invocation invocation) throws Throwable {
        Object returnValue = null;
        long start = 0L;
        MappedStatement mappedStatement = null;
        BoundSql boundSql = null;
        String sqlId = null;
        Configuration configuration = null;

        try {
            mappedStatement = (MappedStatement)invocation.getArgs()[0];
            Object parameter = null;
            if (invocation.getArgs().length > 1) {
                parameter = invocation.getArgs()[1];
            }

            sqlId = mappedStatement.getId();
            boundSql = mappedStatement.getBoundSql(parameter);
            configuration = mappedStatement.getConfiguration();
            start = System.currentTimeMillis();
        } catch (Throwable var15) {
            this._LOGGER.error("error", var15);
        }

        returnValue = invocation.proceed();

        try {
            long end = System.currentTimeMillis();
            long time = end - start;
            String sql;
            if (time >= exceedTime) {
                sql = getSql(configuration, boundSql, sqlId, time);
                this._LOGGER.info("*** sql is *** [{}] *** cost is *** {}ms *** has exceed the limit *** limit is *** {}ms ***", new Object[]{sql.split(":")[1], time, exceedTime});
                return returnValue;
            }

            if (this._LOGGER.isDebugEnabled()) {
                sql = getSql(configuration, boundSql, sqlId, time);
                this._LOGGER.debug("*** sql is *** [{}] *** cost is *** {}ms ***", sql.split(":")[1], time);
            }
        } catch (Throwable var14) {
            this._LOGGER.error("error", var14);
        }

        return returnValue;
    }

    private static String getSql(Configuration configuration, BoundSql boundSql, String sqlId, long time) {
        String sql = showSql(configuration, boundSql);
        StringBuilder str = new StringBuilder(100);
        str.append(sqlId);
        str.append(":");
        str.append(sql);
        str.append(":");
        str.append(time);
        str.append("ms");
        return str.toString();
    }

    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    public void setProperties(Properties properties) {
        if (properties != null) {
            if (!properties.isEmpty()) {
                String exccedtime = properties.getProperty("exccedtime");
                if (exccedtime != null && !"".equals(exccedtime)) {
                    try {
                        long l = Long.parseLong(exccedtime);
                        exceedTime = l;
                    } catch (Exception var5) {
                        this._LOGGER.error("error", var5);
                    }

                }
            }
        }
    }

    private static String getParameterValue(Object obj) {
        String value = null;
        if (obj instanceof String) {
            value = "'" + obj.toString() + "'";
        } else if (obj instanceof Date) {
            DateFormat formatter = DateFormat.getDateTimeInstance(2, 2, Locale.CHINA);
            value = "'" + formatter.format(new Date()) + "'";
        } else if (obj != null) {
            value = obj.toString();
        } else {
            value = "";
        }

        return value;
    }

    private static String showSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (parameterMappings.size() > 0 && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));
            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                Iterator var7 = parameterMappings.iterator();

                while(var7.hasNext()) {
                    ParameterMapping parameterMapping = (ParameterMapping)var7.next();
                    String propertyName = parameterMapping.getProperty();
                    Object obj;
                    if (metaObject.hasGetter(propertyName)) {
                        obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    }
                }
            }
        }

        return sql;
    }
}

PS:紫色部分是配置資料來源對應的Mapper,黃色部分是真正區分不同資料來源對應的Mapper包!