`

Spring+MyBatis多数据源配置实现

阅读更多

  最近用到了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

 

参考文章:http://www.cnblogs.com/lzrabbit/p/3750803.html

  • 大小: 11.3 KB
  • 大小: 9.7 KB
分享到:
评论

相关推荐

    SSM(Spring+SpringMVC+MyBatis)多数据源配置框架

    在多数据源配置中,Spring能够帮助管理不同的数据源,通过配置bean来切换和控制数据源的使用。 **SpringMVC** 是Spring框架的一部分,专为Web开发设计。它简化了模型-视图-控制器(Model-View-Controller,MVC)的...

    Springboot+Mybatis+Druid多数据源配置

    本教程将围绕"Springboot+Mybatis+Druid多数据源配置"这一主题,详细介绍如何实现这一功能。 首先,Spring Boot简化了Spring应用的初始化和配置。在多数据源场景下,我们可以通过Spring Boot的@...

    spring+spring mvc+mybatis框架整合实现超市货物管理系统

    对于MyBatis,我们需要创建`mybatis-config.xml`配置文件,配置数据源、事务管理器以及映射文件的位置。 数据库方面,本系统使用了MySQL,通过MyBatis的SqlSessionFactory和SqlSession对象,我们可以执行SQL语句。`...

    《spring+mybatis 企业应用实战》源码、类库全资料

    1. **配置文件**:包括Spring的bean配置文件(如`applicationContext.xml`)和MyBatis的配置文件(如`mybatis-config.xml`),它们定义了数据源、事务管理器、SqlSessionFactory以及Mapper接口的扫描路径。...

    Springboot+mybatis+druid多数据源配置(oracle+mybatis)

    总结,Spring Boot结合Mybatis和Druid实现多数据源配置的过程包括:配置数据源、配置Mybatis、创建数据源切换器、以及针对不同数据库的测试。这一过程涉及了Spring Boot的自动配置、依赖注入、配置属性绑定等多个...

    Spring+Mybatis 多数据源配置

    这篇博客“Spring+Mybatis 多数据源配置”将深入探讨如何在项目中实现这一功能。 首先,我们需要理解多数据源的概念。在传统的单数据源配置中,所有的数据库访问都指向同一个数据库。而在多数据源环境中,不同的...

    spring+hibernate和spring+myBatis实现连接多个数据库,同时操作的项目

    "spring+hibernate和spring+myBatis实现连接多个数据库,同时操作的项目"是针对这种需求的一个解决方案,旨在提供一种灵活且动态的数据源切换机制。 首先,Spring框架作为Java领域中最受欢迎的应用框架之一,其强大...

    springmvc + spring + mybatis + maven整合配置文件

    然后配置Spring的applicationContext.xml,包括Bean定义、AOP配置、数据源、事务管理器等。接着配置Spring MVC的servlet-context.xml,设置DispatcherServlet、视图解析器、拦截器等。最后,配置MyBatis的mybatis-...

    SpringMvc+Spring+Mybatis+Maven+注解方式=整合

    - MyBatis的配置文件(mybatis-config.xml)中,设置数据源和SqlSessionFactory,以便MyBatis与数据库交互。 通过以上步骤,我们可以构建一个松耦合、可测试的系统,每个组件都发挥着它应有的作用,而注解方式的...

    Spring+SpringMVC+Mybatis多数据源

    总结来说,"Spring+SpringMVC+Mybatis多数据源"的整合涉及了Spring的数据源管理、SpringMVC的请求路由、Mybatis的数据源配置以及事务管理。具体实现时,可以根据项目需求选择合适的方式进行数据源切换,以达到优化...

    struts2+spring+mybatis框架

    3. **配置MyBatis**:编写MyBatis的配置文件,包括数据源、SqlSessionFactory,并为每个Mapper接口定义XML映射文件。 4. **整合Spring和Struts2**:使用Spring的Struts2插件,使Spring管理的Bean可以直接在Struts2 ...

    Struts2+maven+spring+mybatis整合实现注册功能实例

    4. 配置Spring:创建Spring的配置文件(如applicationContext.xml),声明bean,包括Action、Service、DAO以及数据源等。 5. 配置MyBatis:设置mybatis-config.xml,配置数据源和Mapper接口。 6. 编写Service和DAO:...

    springboot+druid+mybatis多数据源动态切换案例

    5. **MyBatis配置**:在多数据源环境下,MyBatis的配置需要针对每个数据源分别设置SqlSessionFactory,并在Mapper接口上通过@MapperScan注解指定对应的SqlSessionFactory。 6. **事务管理**:在多数据源情况下,...

    springboot+mybatis双数据源配置及事务处理

    本教程将深入探讨如何在Spring Boot应用中配置和管理两个不同的数据源,并实现事务处理。 首先,我们需要理解Spring Boot的自动配置特性。Spring Boot通过`@EnableAutoConfiguration`注解自动配置了大量常见服务,...

    SpringBoot+gradle+mybatis多数据源动态配置

    本项目结合了SpringBoot、Gradle和MyBatis,旨在实现多数据源的动态配置,这对于处理多个数据库或者分库分表的场景尤其有用。以下是对这个项目的详细解析: **SpringBoot** SpringBoot是由Pivotal团队提供的全新...

    struts+spring+mybatis源代码例子

    在这个模块中,我们可以期待找到与Struts相关的Action类,Spring的Service和DAO接口及其实现,以及MyBatis的Mapper接口和XML配置文件。这些文件会展示如何在实际场景中操作数据库,处理业务逻辑,并通过Struts的...

    spring+springmvc+mybatis

    在实际项目中,开发者通常会创建一个配置文件(如:`springmvc_mybatis1208`可能包含的`spring-config.xml`),在其中配置Spring和MyBatis的相关设置,包括数据源、事务管理器、SqlSessionFactory等。同时,还需要...

    Spring+mybatis+layui实现增删改查,分页,导入导出功能源代码

    本套源代码实现了Spring 和 mybatis 和 layui 集成情况下的基础操作,包括: 增删改查、分页、导入导出等功能。数据库为mysql,脚本在源代码根目录下,mybatis_crud.sql

Global site tag (gtag.js) - Google Analytics