MyBatis配置多データソース

59392 ワード


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"> <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.xmlvalue> property> <property name="dataSource" ref="projectdataSource" /> bean> <bean id="projectsqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="projectsqlSessionFactory" /> bean> <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.xmlvalue> 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> <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> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation"> <value>classpath:mybatis/mapper.xmlvalue> 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 /> <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"/>
        
        <setting name="lazyLoadingEnabled" value="false"/>
        <setting name="useGeneratedKeys" value="true" />
    settings>
    
    <plugins>
        
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
           
            
            
            
            <property name="offsetAsPageNum" value="false"/>
            
            
            <property name="rowBoundsWithCount" value="false"/>
            
            
            <property name="pageSizeZero" value="false"/>
            
            
            
            <property name="reasonable" value="false"/>
            
            
            
            
            <property name="params" value="pageNum=pageNum;pageSize=pageSize;"/>
            
            <property name="supportMethodsArguments" value="false"/>
            
            <property name="returnPageInfo" value="check"/>
        plugin>
        <plugin interceptor="com.xhl.log.plugins.SqlLogger">
            
            <property name="exccedtime" value="1500"/>
        plugin>
    plugins>
    <mappers>
        <mapper resource="mybatis/mapper_uc_user_detail.xml">mapper> 
    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 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パッケージを区別します.