最近用到了MyBatis配置多数据源,原以为简单配置下就行了,实际操作后发现还是要费些事的,这里记录下,以作备忘。不多废话,直接上代码,后面会有简单的实现介绍。
一.log4j2.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE Configuration> <Configuration status="info" monitorInterval="5"> <Appenders> <Console name="console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5p %c{1}.%M(%F:%L)[%X{serviceId}][%X{bizSeq}][%X{sysSeq}] - %m%n" /> </Console> <RollingFile name="fixedTimeFileAppender" fileName="logs/info.log" filePattern="logs/info.log.%d{yyyy-MM-dd}.%i.log.gz"> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5p %c{1}.%M(%F:%L)[%X{serviceId}][%X{bizSeq}][%X{sysSeq}] - %m%n" /> <Policies> <TimeBasedTriggeringPolicy /> <SizeBasedTriggeringPolicy size="1024 MB" /> </Policies> <DefaultRolloverStrategy max="512" /> </RollingFile> <RollingFile name="timeFixedTimeFileAppender" fileName="logs/timer.log" filePattern="logs/timer.log.%d{yyyy-MM-dd}.%i.log.gz"> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5p %c{1}(%F:%L) - %m%n" /> <Policies> <TimeBasedTriggeringPolicy /> <SizeBasedTriggeringPolicy size="1024 MB" /> </Policies> <DefaultRolloverStrategy max="512" /> </RollingFile> <RollingFile name="myBatisFileAppender" fileName="logs/mybatis.log" filePattern="logs/mybatis.log.%d{yyyy-MM-dd}.%i.log.gz"> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5p %c{2}(%L) - %m%n" /> <Policies> <TimeBasedTriggeringPolicy /> <SizeBasedTriggeringPolicy size="1024 MB" /> </Policies> <DefaultRolloverStrategy max="512" /> </RollingFile> </Appenders> <Loggers> <AsyncLogger name="com.bijian" level="debug" additivity="false" includeLocation="true"> <AppenderRef ref="fixedTimeFileAppender" /> </AsyncLogger> <Logger name="com.bijian.study.dao" level="warn" additivity="false"> <AppenderRef ref="myBatisFileAppender" /> </Logger> <Logger name="org.springframework.jdbc.datasource" level="warn" additivity="false"> <AppenderRef ref="myBatisFileAppender" /> </Logger> <Logger name="druid.sql" level="warn" additivity="false"> <AppenderRef ref="myBatisFileAppender" /> </Logger> <!-- Druid 线程池统计、慢查询监控输出 --> <logger name="com.alibaba.druid" level="warn" additivity="false"> <AppenderRef ref="myBatisFileAppender" /> </logger> <AsyncLogger name="timeLog" level="info" additivity="false"> <AppenderRef ref="timeFixedTimeFileAppender" /> </AsyncLogger> <asyncRoot level="info"> <AppenderRef ref="fixedTimeFileAppender" /> </asyncRoot> </Loggers> </Configuration>
二.database.properties
jdbc.mysql.driver=com.mysql.jdbc.Driver jdbc.mysql.url=jdbc:mysql://192.168.235.1:3306/hbatis?characterEncoding=utf8 jdbc.mysql.username=hbatis jdbc.mysql.password=hbatis12345 jdbc.mysql.driver2=com.mysql.jdbc.Driver jdbc.mysql.url2=jdbc:mysql://192.168.235.2:3306/hbatis?characterEncoding=utf8 jdbc.mysql.username2=hbatis jdbc.mysql.password2=hbatis12345 jdbc.initialSize=5 jdbc.minIdle=5 #druid not need jdbc.maxIdle #jdbc.maxIdle=20 jdbc.maxActive=100 jdbc.maxWait=100000 jdbc.defaultAutoCommit=false jdbc.removeAbandoned=true jdbc.removeAbandonedTimeout=600 jdbc.testWhileIdle=true jdbc.timeBetweenEvictionRunsMillis=60000 jdbc.numTestsPerEvictionRun=20 jdbc.minEvictableIdleTimeMillis=300000
三.单数据源时的Spring配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" 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-3.0.xsd"> <!-- 数据库配置文件 --> <context:property-placeholder location="classpath:/database.properties" /> <!-- 数据源配置 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.mysql.driver}"/> <property name="url" value="${jdbc.mysql.url}"/> <property name="username" value="${jdbc.mysql.username}"/> <property name="password" value="${jdbc.mysql.password}"/> <property name="initialSize" value="${jdbc.initialSize}"/> <property name="minIdle" value="${jdbc.minIdle}"/> <property name="maxIdle" value="${jdbc.maxIdle}"/> <property name="maxActive" value="${jdbc.maxActive}"/> <property name="maxWait" value="${jdbc.maxWait}"/> <property name="defaultAutoCommit" value="${jdbc.defaultAutoCommit}"/> <property name="removeAbandoned" value="${jdbc.removeAbandoned}"/> <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}"/> <property name="testWhileIdle" value="${jdbc.testWhileIdle}"/> <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}"/> <property name="numTestsPerEvictionRun" value="${jdbc.numTestsPerEvictionRun}"/> <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 扫描指定包以获取映射器 --> <bean id="mapperConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.bijian.study.dao" /> </bean> <!-- 自动扫描,多个包以 逗号分隔 --> <context:component-scan base-package="com.bijian.study"/> <aop:aspectj-autoproxy/> </beans>
四.多数据源时Spring配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" 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-3.0.xsd"> <!-- 数据库配置文件 --> <context:property-placeholder location="classpath:/database.properties" /> <!-- 数据源配置 --> <bean id="mySqlDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.mysql.driver}"/> <property name="url" value="${jdbc.mysql.url}"/> <property name="username" value="${jdbc.mysql.username}"/> <property name="password" value="${jdbc.mysql.password}"/> <property name="initialSize" value="${jdbc.initialSize}"/> <property name="minIdle" value="${jdbc.minIdle}"/> <property name="maxIdle" value="${jdbc.maxIdle}"/> <property name="maxActive" value="${jdbc.maxActive}"/> <property name="maxWait" value="${jdbc.maxWait}"/> <property name="defaultAutoCommit" value="${jdbc.defaultAutoCommit}"/> <property name="removeAbandoned" value="${jdbc.removeAbandoned}"/> <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}"/> <property name="testWhileIdle" value="${jdbc.testWhileIdle}"/> <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}"/> <property name="numTestsPerEvictionRun" value="${jdbc.numTestsPerEvictionRun}"/> <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}"/> </bean> <bean id="mySql2DataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.mysql.driver2}"/> <property name="url" value="${jdbc.mysql.url2}"/> <property name="username" value="${jdbc.mysql.username2}"/> <property name="password" value="${jdbc.mysql.password2}"/> <property name="initialSize" value="${jdbc.initialSize}"/> <property name="minIdle" value="${jdbc.minIdle}"/> <property name="maxIdle" value="${jdbc.maxIdle}"/> <property name="maxActive" value="${jdbc.maxActive}"/> <property name="maxWait" value="${jdbc.maxWait}"/> <property name="defaultAutoCommit" value="${jdbc.defaultAutoCommit}"/> <property name="removeAbandoned" value="${jdbc.removeAbandoned}"/> <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}"/> <property name="testWhileIdle" value="${jdbc.testWhileIdle}"/> <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}"/> <property name="numTestsPerEvictionRun" value="${jdbc.numTestsPerEvictionRun}"/> <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}"/> </bean> <bean id="multipleDataSource" class="com.bijian.study.dao.MultipleDataSource"> <property name="defaultTargetDataSource" ref="mySqlDataSource"/> <property name="targetDataSources"> <map> <entry key="mySqlDataSource" value-ref="mySqlDataSource"/> <entry key="mySql2DataSource" value-ref="mySql2DataSource"/> </map> </property> </bean> <!-- sqlSessionFactory对象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--dataSource属性指定要用到的连接池 --> <property name="dataSource" ref="multipleDataSource" /> <!--configLocation属性指定mybatis的核心配置文件 --> <property name="configLocation" value="classpath:Configuration.xml" /> <!-- 可以在Configuration.xml或此处配置映射文件,但其中不能有相同id的parameterMap, resultMap或sql等 --> <property name="mapperLocations" value="classpath*:com/bijian/study/model/*.xml" /> </bean> <!-- 扫描指定包以获取映射器 --> <bean id="mapperConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.bijian.study.dao" /> </bean> <!-- 自动扫描,多个包以 逗号分隔 --> <context:component-scan base-package="com.bijian.study"/> <aop:aspectj-autoproxy/> </beans>
五.MultipleDataSource实现
package com.bijian.study.dao; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; 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(); } }
六.MyBatis接口
package com.bijian.study.dao; import java.util.List; import com.bijian.study.model.Article; import com.bijian.study.model.User; public interface IUserMapper { User getUserById(int id); List<User> getUsers(String name); int addUser(User user); int updateUser(User user); int deleteUser(int id); List<Article> getArticlesByUserId(int id); }
package com.bijian.study.dao; import java.util.List; import com.bijian.study.model.Article; import com.bijian.study.model.User; public interface IUserMapper2 { User getUserById(int id); List<User> getUsers(String name); int addUser(User user); int updateUser(User user); int deleteUser(int id); List<Article> getArticlesByUserId(int id); }
七.Entity实体及Mapping配置
Article.java
package com.bijian.study.model; public class Article { private int id; private User user; private String title; private String content; public int getId() { return id; } public void setId(int id) { this.id = id; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
User.java
package com.bijian.study.model; public class User { private int id; private String name; private int age; private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } // 如果有带参数的构造器,编译器不会自动生成无参构造器。当查询需要返回对象时,ORM框架用反射来调用对象的无参构造函数,导致异常:java.lang.NoSuchMethodException: com.bijian.study.model.User.<init>() // 这时需要明确写出: public User() { } public User(int id, String address) { this.id = id; this.address = address; } public User(String name, int age, String address) { this.name = name; this.age = age; this.address = address; } }
User.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.bijian.study.dao.IUserMapper"> <select id="getUserById" parameterType="int" resultType="User"> select * from `user` where id = #{id} </select> <resultMap type="User" id="userList"><!-- type为返回列表元素的类全名或别名 --> <id column="id" property="id" /> <result column="name" property="name" /> <result column="age" property="age" /> <result column="address" property="address" /> </resultMap> <select id="getUsers" parameterType="string" resultMap="userList"><!-- resultMap为上面定义的User列表 --> select * from `user` where name like #{name} </select> <insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id"> <!-- useGeneratedKeys指定myBatis使用数据库自动生成的主键,并填充到keyProperty指定的属性上。如果未指定,返回对象拿不到生成的值 --> insert into user(name,age,address) values(#{name},#{age},#{address}) </insert> <update id="updateUser" parameterType="User"> update `user` set name=#{name}, age=#{age}, address=#{address} where id=#{id} </update> <delete id="deleteUser" parameterType="int"> delete from `user` where id=#{id} </delete> <resultMap type="com.bijian.study.model.Article" id="articleList"> <id column="a_id" property="id" /> <result column="title" property="title" /> <result column="content" property="content" /> <!-- user属性映射到User类 --> <!-- <association property="user" javaType="User"> <id column="id" property="id" /> <result column="name" property="name" /> <result column="address" property="address" /> </association> --> <association property="user" javaType="User" resultMap="userList"/> </resultMap> <select id="getArticlesByUserId" parameterType="int" resultMap="articleList"> select u.id, u.name, u.age, u.address, a.id a_id, a.title, a.content from article a inner join user u on a.user_id=u.id and u.id=#{id} </select> </mapper>
User2.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.bijian.study.dao.IUserMapper2"> <select id="getUserById" parameterType="int" resultType="User"> select * from `user` where id = #{id} </select> <resultMap type="User" id="userList"><!-- type为返回列表元素的类全名或别名 --> <id column="id" property="id" /> <result column="name" property="name" /> <result column="age" property="age" /> <result column="address" property="address" /> </resultMap> <select id="getUsers" parameterType="string" resultMap="userList"><!-- resultMap为上面定义的User列表 --> select * from `user` where name like #{name} </select> <insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id"> <!-- useGeneratedKeys指定myBatis使用数据库自动生成的主键,并填充到keyProperty指定的属性上。如果未指定,返回对象拿不到生成的值 --> insert into user(name,age,address) values(#{name},#{age},#{address}) </insert> <update id="updateUser" parameterType="User"> update `user` set name=#{name}, age=#{age}, address=#{address} where id=#{id} </update> <delete id="deleteUser" parameterType="int"> delete from `user` where id=#{id} </delete> <resultMap type="com.bijian.study.model.Article" id="articleList"> <id column="a_id" property="id" /> <result column="title" property="title" /> <result column="content" property="content" /> <!-- user属性映射到User类 --> <!-- <association property="user" javaType="User"> <id column="id" property="id" /> <result column="name" property="name" /> <result column="address" property="address" /> </association> --> <association property="user" javaType="User" resultMap="userList"/> </resultMap> <select id="getArticlesByUserId" parameterType="int" resultMap="articleList"> select u.id, u.name, u.age, u.address, a.id a_id, a.title, a.content from article a inner join user u on a.user_id=u.id and u.id=#{id} </select> </mapper>
八.手动数据源切换调用
package com.bijian.test; import java.util.List; import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.bijian.study.dao.IUserMapper; import com.bijian.study.dao.IUserMapper2; import com.bijian.study.dao.MultipleDataSource; import com.bijian.study.model.Article; public class Main { public static void main(String[] args) { //初始化ApplicationContext ApplicationContext applicationContext = new ClassPathXmlApplicationContext("file:E:/develop/eclipse/workspace/SpringMVC/WebContent/WEB-INF/applicationContext.xml"); DataSource mySqlDataSource = (DataSource)applicationContext.getBean("mySqlDataSource"); System.out.println("mySqlDataSource:" + mySqlDataSource); IUserMapper mySqlMapper = applicationContext.getBean(IUserMapper.class); IUserMapper2 mySqlMapper2 = applicationContext.getBean(IUserMapper2.class); //设置数据源为MySql,使用了AOP测试时请将下面这行注释 MultipleDataSource.setDataSourceKey("mySqlDataSource"); List<Article> articles = mySqlMapper.getArticlesByUserId(1); for(Article acticle : articles) { System.out.println(acticle.getTitle()); } //设置数据源为SqlServer,使用AOP测试时请将下面这行注释 MultipleDataSource.setDataSourceKey("mySql2DataSource"); List<Article> articles2 = mySqlMapper2.getArticlesByUserId(2); for(Article acticle : articles2) { System.out.println(acticle.getTitle()); } } }
运行结果如下:
title1 title2 title3 title4 test1 test2 test3 test4
结合如下对应数据库中的数据不难发现运行结果正确。
jdbc.mysql.url对应的数据库表数据如下所示:
jdbc.mysql.url2对应的数据库表数据如下所示:
PS:上面是dbcp数据连接池,我们可以改成druid连接池如下,这里引用的是druid-1.1.3.jar
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" 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-3.0.xsd"> <!-- 数据库配置文件 --> <context:property-placeholder location="classpath:/database.properties" /> <!-- 数据源配置 --> <bean id="mySqlDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 基本属性 url、user、password --> <property name="url" value="${jdbc.mysql.url}" /> <property name="username" value="${jdbc.mysql.username}" /> <property name="password" value="${jdbc.mysql.password}"/> <!-- 配置初始化大小、最小、最大、是否保活 --> <property name="initialSize" value="${jdbc.initialSize}" /> <property name="minIdle" value="${jdbc.minIdle}" /> <property name="maxActive" value="${jdbc.maxActive}" /> <property name="keepAlive" value="true" /> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="${jdbc.maxWait}" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" /> <!-- 检测语句利用 MySQL 的轻量级 ping 机制 --> <property name="validationQuery" value="/* ping */ SELECT 1" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <!-- 打开PSCache,并且指定每个连接上PSCache的大小。Oracle 才用的着, MySQL 关闭 --> <property name="poolPreparedStatements" value="false" /> <!-- 测试环境:打开removeAbandoned功能,超时时间单位是秒 --> <property name="removeAbandoned" value="true" /> <property name="removeAbandonedTimeout" value="60" /> <property name="logAbandoned" value="true" /> <!-- 配置监控统计filters --> <property name="filters" value="slf4j" /> <!-- 配置监控统计filters --> <property name="proxyFilters"> <list> <ref bean="stat-filter" /> </list> </property> </bean> <bean id="stat-filter" class="com.alibaba.druid.filter.stat.StatFilter"> <!-- SQL 慢查询的时长 --> <property name="slowSqlMillis" value="250" /> <property name="logSlowSql" value="true" /> <property name="mergeSql" value="true" /> </bean> <bean id="mySql2DataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 基本属性 url、user、password --> <property name="url" value="${jdbc.mysql.url2}" /> <property name="username" value="${jdbc.mysql.username2}" /> <property name="password" value="${jdbc.mysql.password2}"/> <!-- 配置初始化大小、最小、最大、是否保活 --> <property name="initialSize" value="${jdbc.initialSize}" /> <property name="minIdle" value="${jdbc.minIdle}" /> <property name="maxActive" value="${jdbc.maxActive}" /> <property name="keepAlive" value="true" /> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="${jdbc.maxWait}" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" /> <!-- 检测语句利用 MySQL 的轻量级 ping 机制 --> <property name="validationQuery" value="/* ping */ SELECT 1" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <!-- 打开PSCache,并且指定每个连接上PSCache的大小。Oracle 才用的着, MySQL 关闭 --> <property name="poolPreparedStatements" value="false" /> <!-- 测试环境:打开removeAbandoned功能,超时时间单位是秒 --> <property name="removeAbandoned" value="true" /> <property name="removeAbandonedTimeout" value="60" /> <property name="logAbandoned" value="true" /> <!-- 配置监控统计filters --> <property name="filters" value="slf4j" /> <!-- 配置监控统计filters --> <property name="proxyFilters"> <list> <ref bean="stat-filter" /> </list> </property> </bean> <bean id="multipleDataSource" class="com.bijian.study.dao.MultipleDataSource"> <property name="defaultTargetDataSource" ref="mySqlDataSource"/> <property name="targetDataSources"> <map> <entry key="mySqlDataSource" value-ref="mySqlDataSource"/> <entry key="mySql2DataSource" value-ref="mySql2DataSource"/> </map> </property> </bean> <!-- sqlSessionFactory对象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--dataSource属性指定要用到的连接池 --> <property name="dataSource" ref="multipleDataSource" /> <!--configLocation属性指定mybatis的核心配置文件 --> <property name="configLocation" value="classpath:Configuration.xml" /> <!-- 可以在Configuration.xml或此处配置映射文件,但其中不能有相同id的parameterMap, resultMap或sql等 --> <property name="mapperLocations" value="classpath*:com/bijian/study/model/*.xml" /> </bean> <!-- 扫描指定包以获取映射器 --> <bean id="mapperConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.bijian.study.dao" /> </bean> <!-- 自动扫描,多个包以 逗号分隔 --> <context:component-scan base-package="com.bijian.study"/> <aop:aspectj-autoproxy/> </beans>
运行Main.java结果如下:
14:20:24.422 [main] INFO com.alibaba.druid.pool.DruidDataSource - {dataSource-1} inited 14:20:24.632 [main] INFO com.alibaba.druid.pool.DruidDataSource - {dataSource-2} inited mySqlDataSource:{ CreateTime:"2018-12-23 14:20:23", ActiveCount:0, PoolingCount:5, CreateCount:5, DestroyCount:0, CloseCount:0, ConnectCount:0, Connections:[ {ID:1207231495, ConnectTime:"2018-12-23 14:20:24", UseCount:0, LastActiveTime:"2018-12-23 14:20:24"}, {ID:756936249, ConnectTime:"2018-12-23 14:20:24", UseCount:0, LastActiveTime:"2018-12-23 14:20:24"}, {ID:1221981006, ConnectTime:"2018-12-23 14:20:24", UseCount:0, LastActiveTime:"2018-12-23 14:20:24"}, {ID:264394929, ConnectTime:"2018-12-23 14:20:24", UseCount:0, LastActiveTime:"2018-12-23 14:20:24"}, {ID:1878413714, ConnectTime:"2018-12-23 14:20:24", UseCount:0, LastActiveTime:"2018-12-23 14:20:24"} ] } title1 title2 title3 title4 test1 test2 test3 test4
相关推荐
SSM(Spring+SpringMVC+MyBatis)多数据源配置框架,精简版
springboot+mybatis双数据源配置及事务处理
多数据源配置,使用了数据库连接池,并且是多数据源,分也不要多了,2分,有什么疑问可以指出,或者不足也可以一起学习
Spring+SpringMVC+Mybatis多数据源整合。基于spring3.0和mybatis3.2的
技术架构:springboot2.0 + mybatis + druid, 数据库:Oracle,Mysql 数据库分离调试,针对不同数据库情况
springboot+druid+mybatis多数据源动态切换,基于sql类型完成读写分离操作
springboot + mybatis(通用mapper) + HikariCP(比durid更快)多数据源,从此单表的xml文件和crud就不需要自己写了
本套源代码实现了Spring 和 mybatis 和 layui 集成情况下的基础操作,包括: 增删改查、分页、导入导出等功能。数据库为mysql,脚本在源代码根目录下,mybatis_crud.sql
spring+springmvc+mybatis多数据源.
项目中我们经常会遇到多数据源的问题,尤其是数据同步或定时任务等项目更是如此。多数据源让人最头痛的,不是配置多个数据源,而是如何能灵活动态的切换数据源。 此项目就是为了解决这个问题。
spring+mybatis 多个数据源调用示例
SpringBoot + mybatis-plus + druid 实现mySql与Orcl双数据源
spring+SpringMVC+MyBatis之配置多数据源
springboot+mybatis多数据源配置整合。一个最简单的测试用例。实现了数据库数据处理及springboot多数据源问题。亲测
本篇文章主要介绍了Spring+MyBatis多数据源配置实现示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
Spring+SpringMVC+Mybatis多数据源整合,修改相关配置可以直接使用。
spring +springboot+mybatis+maven 读写分离,数据库采用mysql, 采用springboot 采用项目框架搭建,继承spring 中的AbstractRoutingDataSource,实现 determineCurrentLookupKey 进行数据源的动态切换,采用Spring ...
spring+mybatis 数据路由JAR包,实现事物级控制,读写库多次分离,非cloud 配置中心。