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包!