Spring+MyBatis双数据库配置

Spring+MyBatis双数据库配置

近期项目中遇到要调用其它数据库的情况。本来仅仅使用一个MySQL数据库。但随着项目内容越来越多,逻辑越来越复杂。

原来一个数据库已经不够用了,须要分库分表。所以决定扩充数据库,正好Spring能够灵活的扩充数据库。以下简单写一篇博文,记录下多数据库配置的过程。

1.项目结构例如以下图:

当中mkhl和ulab分别相应两个数据库模块。同一时候也相应两个不同的功能模块。

2.整个Maven项目的配置文件:pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>ULAB_UsersProvider</groupId>
	<artifactId>ULAB_UsersProvider</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>ULAB_UsersProvider</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<spring.version>4.0.0.RELEASE</spring.version>
		<jackson.version>2.5.0</jackson.version>
	</properties>

	<dependencies>
		<!-- junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.8.1</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>javax.activation</groupId>
			<artifactId>activation</artifactId>
			<version>1.1</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>

		<!-- spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- dubbo -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>dubbo</artifactId>
			<version>2.5.3</version>
		</dependency>

		<!-- zookeeper -->
		<dependency>
			<groupId>org.apache.zookeeper</groupId>
			<artifactId>zookeeper</artifactId>
			<version>3.4.6</version>
		</dependency>
		<dependency>
			<groupId>com.github.sgroschupf</groupId>
			<artifactId>zkclient</artifactId>
			<version>0.1</version>
		</dependency>

		<!-- mysql连接 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.34</version>
		</dependency>

		<dependency>
			<groupId>commons-pool</groupId>
			<artifactId>commons-pool</artifactId>
			<version>1.6</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>

		<!-- oracle连接 -->
		<!-- <dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc14</artifactId>
			<version>10.2.0.1.0</version>
		</dependency> -->

        <!-- SQL Server连接 -->
        <dependency>
          <groupId>com.microsoft.sqlserver</groupId>
          <artifactId>sqljdbc4</artifactId>
          <version>4.0</version>
        </dependency>

		<!-- 数据源 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.12</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.8.4</version>
		</dependency>

		<!-- ehcache -->
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache-core</artifactId>
			<version>2.6.10</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-ehcache</artifactId>
			<version>1.0.0</version>
		</dependency>

		<!-- log4j -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<dependency>
			<groupId>com.googlecode.log4jdbc</groupId>
			<artifactId>log4jdbc</artifactId>
			<version>1.2</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>net.bull.javamelody</groupId>
			<artifactId>javamelody-core</artifactId>
			<version>1.50.0</version>
		</dependency>

		<!-- servlet -->
		<!-- <dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency> -->

		<!-- json -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.13</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.3</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>${jackson.version}</version>
		</dependency>

		<!-- mybatis核心包 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.2.4</version>
		</dependency>

		<!-- mybatis/spring包 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.2</version>
		</dependency>

		<!-- 文件上传 -->
		<!-- <dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>jexcelapi</groupId>
			<artifactId>jxl</artifactId>
			<version>2.4.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.9</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.9</version>
		</dependency> -->

		<!-- <dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.0.0</version>
			<type>jar</type>
		</dependency> 

		<dependency>
			<groupId>javax.xml.rpc</groupId>
			<artifactId>javax.xml.rpc-api</artifactId>
			<version>1.1.1</version>
		</dependency>

		<dependency>
			<groupId>wsdl4j</groupId>
			<artifactId>wsdl4j</artifactId>
			<version>1.6.3</version>
		</dependency>

		<dependency>
			<groupId>org.codehaus.xfire</groupId>
			<artifactId>xfire-all</artifactId>
			<version>1.2.6</version>
		</dependency> -->

		<!-- axis2 -->
		<!-- <dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-aar-maven-plugin</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-adb</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-adb-codegen</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-ant-plugin</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-clustering</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-codegen</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-integration</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-java2wsdl</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-java2wsdl-maven-plugin</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-jaxbri</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-jaxws</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-jaxws-integration</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-jibx</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-json</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-kernel</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-mar-maven-plugin</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-metadata</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-mtompolicy</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-repo-maven-plugin</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-resource-bundle</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-saaj</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-soapmonitor-servlet</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-spring</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-transport-http</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-transport-local</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-wsdl2code-maven-plugin</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-xmlbeans</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>org.apache.axis2.osgi</artifactId>
			<version>1.6.2</version>
		</dependency> -->

		<!-- Mybatis_pagehelper -->
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
			<version>4.0.1</version>
		</dependency>

	</dependencies>

	<build>
		<finalName>ULAB_UsersProvider1.0</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-shade-plugin</artifactId>
				<version>1.4</version>
				<executions>
					<execution>
						<phase>package</phase>
						<goals>
							<goal>shade</goal>
						</goals>
						<configuration>
							<filters>
								<filter>
									<artifact>*:*</artifact>
									<excludes>
										<exclude>META-INF/*.SF</exclude>
										<exclude>META-INF/*.DSA</exclude>
										<exclude>META-INF/*.RSA</exclude>
									</excludes>
								</filter>
							</filters>
							<transformers>
								<transformer
									implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
									<mainClass>com.ouc.ulab.main.UsersProvider</mainClass>
								</transformer>
								<transformer
									implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
									<resource>META-INF/spring.handlers</resource>
								</transformer>
								<transformer
									implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
									<resource>META-INF/spring.schemas</resource>
								</transformer>
							</transformers>
						</configuration>
					</execution>
				</executions>
			</plugin>

		</plugins>

	</build>
</project>

3.接下来介绍与Spring和MyBatis相关的配置文件:

1)数据库配置文件:jdbc.properties

#jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
#jdbc.url=jdbc\:oracle\:thin\:@192.168.151.239\:1521\:orcl
#jdbc.username=ULab
#jdbc.password=123456
#jdbc.validationQuery=SELECT 1 FROM DUAL

jdbc.B.driverClassName=com.mysql.jdbc.Driver
jdbc.B.url=jdbc\:mysql\://110.126.70.48\:3310/ulab?useUnicode\=true&characterEncoding\=UTF-8
jdbc.B.username=mkhl
jdbc.B.password=123456

jdbc.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc\:sqlserver\://110.135.60.233\:1433;DatabaseName=OUCJiance
jdbc.username=OUCUser
jdbc.password=OUC,789

jdbc.initialSize=1
jdbc.maxActive=20
jdbc.minIdle=0
jdbc.maxWait=60000
jdbc.validationQuery=SELECT 1
jdbc.testOnBorrow=false
jdbc.testOnReturn=false
jdbc.testWhileIdle=true
jdbc.timeBetweenEvictionRunsMillis=60000
jdbc.minEvictableIdleTimeMillis=25200000
jdbc.removeAbandoned=true
jdbc.removeAbandonedTimeout=1800
jdbc.logAbandoned=true
jdbc.filters=stat

2)ehcache缓存配置:ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" monitoring="autodetect"
         dynamicConfig="true">
<diskStore path="java.io.tmpdir" />
<defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            diskSpoolBufferSizeMB="30"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
            />
    <cache name="mavenCache"
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            diskSpoolBufferSizeMB="30"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
            />
</ehcache> 

3)日志配置:log4j.properties

log4j.rootLogger=INFO,stdout,logfile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n  

log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.File=D:/log4j/U-LAB/usersProvide_log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} %-5p [%t] %c.%M(%L) - %m%n

log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug,stdout

log4j.logger.jdbc.sqlonly=OFF
log4j.logger.jdbc.sqltiming=OFF
log4j.logger.jdbc.audit=OFF
log4j.logger.jdbc.resultset=OFF
log4j.logger.jdbc.connection=OFF

4)mybatis基础配置:mybatis-configure.xml

<?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="cacheEnabled" value="true" />
 	 <setting name="jdbcTypeForNull" value="NULL" />
   </settings>
</configuration>   

5)数据库连接池Druid配置:spring-druid.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xmlns:task="http://www.springframework.org/schema/task"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">   

	<!-- 配置druid监控spring jdbc -->
	<bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor" />

	<bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
		<property name="patterns">
			<list>
				<value>com.ouc.ulab.service.*</value>
				<value>com.ouc.mkhl.service.*</value>
			</list>
		</property>
	</bean>
	<aop:config>
		<aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
	</aop:config>

</beans>

6)MyBatis数据库相关的配置,双数据库配置主要内容在这里:spring-mybatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache"
	xmlns:task="http://www.springframework.org/schema/task" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

	<!-- 配置数据源1:SQLServer -->
	<bean name="dataSource1" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<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="maxActive" value="${jdbc.maxActive}" />
		<!-- 连接池最小空暇 -->
		<property name="minIdle" value="${jdbc.minIdle}" />
		<!-- 获取连接最大等待时间 -->
		<property name="maxWait" value="${jdbc.maxWait}" />

		<property name="validationQuery" value="${jdbc.validationQuery}" />
		<property name="testOnBorrow" value="${jdbc.testOnBorrow}" />
		<property name="testOnReturn" value="${jdbc.testOnReturn}" />
		<property name="testWhileIdle" value="${jdbc.testWhileIdle}" />

		<!-- 配置间隔多久才进行一次检測。检測须要关闭的空暇连接。单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" />
		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" />

		<!-- 打开removeAbandoned功能 -->
		<property name="removeAbandoned" value="${jdbc.removeAbandoned}" />
		<!-- 1800秒,也就是30分钟 -->
		<property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" />
		<!-- 关闭abanded连接时输出错误日志 -->
		<property name="logAbandoned" value="${jdbc.logAbandoned}" />

		<!-- 监控数据库 -->
		<property name="filters" value="${jdbc.filters}" />
	</bean>

    <!-- 配置数据源2:MySQL -->
	<bean name="dataSource2" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<property name="driverClassName" value="${jdbc.B.driverClassName}" />
		<property name="url" value="${jdbc.B.url}" />
		<property name="username" value="${jdbc.B.username}" />
		<property name="password" value="${jdbc.B.password}" />

		<!-- 初始化连接大小 -->
		<property name="initialSize" value="${jdbc.initialSize}" />
		<!-- 连接池最大使用连接数量 -->
		<property name="maxActive" value="${jdbc.maxActive}" />
		<!-- 连接池最小空暇 -->
		<property name="minIdle" value="${jdbc.minIdle}" />
		<!-- 获取连接最大等待时间 -->
		<property name="maxWait" value="${jdbc.maxWait}" />

		<property name="validationQuery" value="${jdbc.validationQuery}" />
		<property name="testOnBorrow" value="${jdbc.testOnBorrow}" />
		<property name="testOnReturn" value="${jdbc.testOnReturn}" />
		<property name="testWhileIdle" value="${jdbc.testWhileIdle}" />

		<!-- 配置间隔多久才进行一次检測,检測须要关闭的空暇连接。单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" />
		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" />

		<!-- 打开removeAbandoned功能 -->
		<property name="removeAbandoned" value="${jdbc.removeAbandoned}" />
		<!-- 1800秒,也就是30分钟 -->
		<property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" />
		<!-- 关闭abanded连接时输出错误日志 -->
		<property name="logAbandoned" value="${jdbc.logAbandoned}" />

		<!-- 监控数据库 -->
		<property name="filters" value="${jdbc.filters}" />
	</bean>

	<!-- myBatis文件 -->
	<bean id="sqlSessionFactory1" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource1" />
		<property name="mapperLocations" value="classpath:com/ouc/ulab/mapping/*.xml" />
		<property name="typeAliasesPackage" value="com.ouc.ulab.model" />
		<property name="plugins">
			<array>
				<bean class="com.github.pagehelper.PageHelper">
					<property name="properties">
						<value>
							dialect=sqlserver
						</value>
					</property>
				</bean>
			</array>
		</property>
		<property name="configLocation" value="classpath:mybatis-configure.xml" />
	</bean>

    <bean id="sqlSessionFactory2" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource2" />
		<property name="mapperLocations" value="classpath:com/ouc/mkhl/mapping/*.xml" />
		<property name="typeAliasesPackage" value="com.ouc.mkhl.model" />
		<property name="configLocation" value="classpath:mybatis-configure.xml" />
	</bean>

	<bean id = "mapperScannerConfigurer1" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.ouc.ulab.dao" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory1" />
	</bean>

    <bean id = "mapperScannerConfigurer2" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.ouc.mkhl.dao" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory2" />
	</bean>

	<!-- 事务管理 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource1" />
	</bean>

</beans>

7)Spring中Bean的注解扫描识别配置:spring.xml,此处为了公布Dubbo服务。

<?

xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/util
       http://www.springframework.org/schema/util/spring-util-3.1.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <aop:aspectj-autoproxy/>
    <!-- 自己主动扫描含有@Service将其注入为bean -->
	<context:component-scan base-package="com.ouc.ulab.service"/>
	<context:component-scan base-package="com.ouc.ulab.service.impl"/>
	<context:component-scan base-package="com.ouc.mkhl.service"/>
	<context:component-scan base-package="com.ouc.mkhl.service.impl"/>

	<context:annotation-config />
	<!--引入配置属性文件  -->
	<context:property-placeholder location="classpath:jdbc.properties"/>
</beans>

8)公布Dubbo接口配置:spring-dubbo.xml,此处配置注冊中心地址,公布接口等内容。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://code.alibabatech.com/schema/dubbo
        http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

	<!-- 提供方应用信息,用于计算依赖关系 -->
	<dubbo:application name="ULAB_DubboProvider" />

	<!-- 使用multicast广播注冊中心暴露服务地址 <dubbo:registry address="multicast://224.5.6.7:1234" /> -->

	<dubbo:registry id="localUsersRegistry" address="zookeeper://127.0.0.1:2181"></dubbo:registry>

    <!-- 用dubbo协议在21000端口暴露服务 -->
	<dubbo:protocol name="dubbo" port="21000" />

	<!-- 声明须要暴露的服务接口 -->
	<dubbo:service interface="com.ouc.ulab.service.VSupplierUsersService" ref="vSupplierUsersService" registry="localUsersRegistry" />

	<dubbo:service interface="com.ouc.mkhl.service.UsersEvaluateService" ref="usersEvaluateService" registry="localUsersRegistry" />

</beans>

4.下面以ulab模块为例,介绍相关的功能包:dao。model,mapping,service,service.impl,main。

1)model数据库表实体类包:VSupplyUser类

package com.ouc.ulab.model;

import java.io.Serializable;

public class VSupplyUser implements Serializable {

    private static final long serialVersionUID = 12L;

    private String supplycode;

    private String supplyname;

    private String supplypass;

    public String getSupplycode() {
        return supplycode;
    }

    public void setSupplycode(String supplycode) {
        this.supplycode = supplycode == null ?

null : supplycode.trim();
    }

    public String getSupplyname() {
        return supplyname;
    }

    public void setSupplyname(String supplyname) {
        this.supplyname = supplyname == null ? null : supplyname.trim();
    }

    public String getSupplypass() {
        return supplypass;
    }

    public void setSupplypass(String supplypass) {
        this.supplypass = supplypass == null ?

null : supplypass.trim();
    }
}

2)数据接口Dao包:VSupplyUserMapper

package com.ouc.ulab.dao;

import java.util.List;

import com.ouc.ulab.model.VSupplyUser;

public interface VSupplyUserMapper {

    int insert(VSupplyUser record);

    int insertSelective(VSupplyUser record);

    public VSupplyUser getVSupplyUserByCode(String supplycode);

    public List <VSupplyUser> getAllVSupplyUser();

}

3)SQL语句配置包:VSupplyUserMapper.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.ouc.ulab.dao.VSupplyUserMapper" >
  <resultMap id="BaseResultMap" type="VSupplyUser" >
    <result column="SupplyCode" property="supplycode" jdbcType="NVARCHAR" />
    <result column="SupplyName" property="supplyname" jdbcType="NVARCHAR" />
    <result column="SupplyPass" property="supplypass" jdbcType="NVARCHAR" />
  </resultMap>

  <select id="getVSupplyUserByCode" resultType="VSupplyUser" parameterType="java.lang.String" >
    select * from V_SupplyUser
    where SupplyCode = #{#{supplycode,jdbcType=NVARCHAR}
  </select>

  <select id="getAllVSupplyUser" resultMap="BaseResultMap" >
    select * from V_SupplyUser
  </select>

  <insert id="insert" parameterType="VSupplyUser" >
    insert into V_SupplyUser (SupplyCode, SupplyName, SupplyPass
      )
    values (#{supplycode,jdbcType=NVARCHAR}, #{supplyname,jdbcType=NVARCHAR}, #{supplypass,jdbcType=NVARCHAR}
      )
  </insert>
  <insert id="insertSelective" parameterType="VSupplyUser" >
    insert into V_SupplyUser
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="supplycode != null" >
        SupplyCode,
      </if>
      <if test="supplyname != null" >
        SupplyName,
      </if>
      <if test="supplypass != null" >
        SupplyPass,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="supplycode != null" >
        #{supplycode,jdbcType=NVARCHAR},
      </if>
      <if test="supplyname != null" >
        #{supplyname,jdbcType=NVARCHAR},
      </if>
      <if test="supplypass != null" >
        #{supplypass,jdbcType=NVARCHAR},
      </if>
    </trim>
  </insert>
</mapper>

4)Dubbo服务接口包:VSupplierUsersService

package com.ouc.ulab.service;

import java.util.List;

import com.ouc.ulab.model.VSupplyUser;

public interface VSupplierUsersService {

	public VSupplyUser getVSupplyUserByCode(String supplycode);

	public List <VSupplyUser> getAllVSupplyUser();
}

5)Dubbo服务接口详细实现包:VSupplierUsersSerImpl

package com.ouc.ulab.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ouc.ulab.dao.VSupplyUserMapper;
import com.ouc.ulab.model.VSupplyUser;
import com.ouc.ulab.service.VSupplierUsersService;

@Service("vSupplierUsersService")
public class VSupplierUsersSerImpl implements VSupplierUsersService{

	@Autowired  VSupplyUserMapper vSuppUserMapper;

	@Override
	public VSupplyUser getVSupplyUserByCode(String supplycode){
	     return vSuppUserMapper.getVSupplyUserByCode(supplycode);
	}

	@Override
	public List <VSupplyUser> getAllVSupplyUser(){
	    return vSuppUserMapper.getAllVSupplyUser();
	}
}

5.公布接口測试Main:UsersProvider

package com.ouc.ulab.main;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ouc.ulab.service.VSupplierUsersService;
import com.ouc.ulab.model.VSupplyUser;
import com.ouc.mkhl.service.UsersEvaluateService;
import com.ouc.mkhl.model.PlanCount;

public class UsersProvider {

    private static VSupplierUsersService vSuppUsersSer;

    private static UsersEvaluateService usersEvaluateSer;

    @Autowired
    public static void main(String[] args) throws Exception {
	try {
	    @SuppressWarnings("resource")
	    ClassPathXmlApplicationContext cxt = new ClassPathXmlApplicationContext(
		    new String[] { "classpath:spring.xml",
			    "classpath:spring-mybatis.xml",
			    "classpath:spring-dubbo.xml" });

	    cxt.start();

	    vSuppUsersSer = (VSupplierUsersService) cxt
		    .getBean("vSupplierUsersService");

	    String supplyCode = "V98758";
	    VSupplyUser user = vSuppUsersSer.getVSupplyUserByCode(supplyCode);
	    System.out.println("供应商用户信息:");
	    System.out.println("V码:" + user.getSupplycode());
	    System.out.println("供应商名称:" + user.getSupplyname());
	    System.out.println("供应商登录password:" + user.getSupplypass());

	    List<VSupplyUser> supplyUserList = new ArrayList<VSupplyUser>();
	    supplyUserList = vSuppUsersSer.getAllVSupplyUser();
	    System.out.println("供应商用户总量:"+supplyUserList.size());

	    usersEvaluateSer = (UsersEvaluateService) cxt.getBean("usersEvaluateService");
	    List<PlanCount> planCountList = new ArrayList<PlanCount>();
	    planCountList = usersEvaluateSer.getPlanCountByYearAndVCode("2016", "V13187");
	    System.out.println("问题方案统计结果:" + planCountList.size());

	    PlanCount planCount = new PlanCount();
	    planCount = usersEvaluateSer.getPlanCountByYearAndMonthAndVCode("2016", "V13187", 4);
	    System.out.println("问题方案:" + planCount.getPlanNum() + planCount.getQuestionNum());

	    System.in.read(); // 模拟开启

	} catch (Exception e) {
	    e.printStackTrace();
	    System.out.println(e.getMessage());
	    Logger log = Logger.getLogger(UsersProvider.class);
	    log.error(e.getMessage()); // 将异常输出到文件
	}

    }
}

6.执行结果例如以下图:

以上数据库分库已经大功告成,以后在与大家具体介绍怎样分表。以及分表的原则。

文章中如有错误,欢迎高手指正,本人是一个小菜鸟。正在努力学习中。

时间: 2024-10-12 04:19:56

Spring+MyBatis双数据库配置的相关文章

spring+mybatis 多数据库配置

这几天需要在ssm项目中配置多一个数据库,就去网上找多数据源的例子,发现都没有成功就自己试了下自己写的 原理: 创建两个数据源,两个seesionFactory,两个事务管理器,然后两个事务管理器分别配置aop,扫描不同的package(网上看到的都是使用注解方式,这里使用aop方式) 1.环境: Mybatis + springmvc +spring + druid + log4j 如果没使用druid  的话将将数据源的bean 修改回org.apache.commons.dbcp.Basi

spring,mybatis事务管理配置与@Transactional注解使用

spring,mybatis事务管理配置与@Transactional注解使用[转] 概述事务管理对于企业应用来说是至关重要的,即使出现异常情况,它也可以保证数据的一致性.Spring Framework对事务管理提供了一致的抽象,其特点如下: 为不同的事务API提供一致的编程模型,比如JTA(Java Transaction API), JDBC, Hibernate, JPA(Java Persistence API和JDO(Java Data Objects) 支持声明式事务管理,特别是基

spring,mybatis事务管理配置与@Transactional注解使用[转]

spring,mybatis事务管理配置与@Transactional注解使用[转] spring,mybatis事务管理配置与@Transactional注解使用 概述事务管理对于企业应用来说是至关重要的,即使出现异常情况,它也可以保证数据的一致性.Spring Framework对事务管理提供了一致的抽象,其特点如下: 为不同的事务API提供一致的编程模型,比如JTA(Java Transaction API), JDBC, Hibernate, JPA(Java Persistence A

Spring+MyBatis实现数据库读写分离方案

方案1通过MyBatis配置文件创建读写分离两个DataSource,每个SqlSessionFactoryBean对象的mapperLocations属性制定两个读写数据源的配置文件.将所有读的操作配置在读文件中,所有写的操作配置在写文件中. 优点:实现简单缺点:维护麻烦,需要对原有的xml文件进行重新修改,不支持多读,不易扩展实现方式 <bean id="abstractDataSource" abstract="true" class="com

Spring+Mybatis+Maven 整合配置

1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans default-autowire="byName" 3 xmlns="http://www.springframework.org/schema/beans" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:sche

Spring+Mybatis多数据库的配置

场景:在Spring+Mybatis搭建的项目中要在配置两个数据库,如何实现? 其实也不是多难的事情,只要把配置配好了,一切问题就迎刃而解了,废话不多说,且看 如下配置-- 配置一:jdbc.properties 配置两个数据库:myuser和myitem myuser.jdbc.driver=com.mysql.jdbc.Driver myuser.jdbc.url=jdbc:mysql://192.168.1.100:3306/myuser?useUnicode=true&zeroDateT

springMVC+spring+mybatis多数据源配置

1.application.properties配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="htt

spring mybatis 多数据源配置

项目上遇到多数据源的问题,分别是阿里的DRDS和ADB数据库,他们的语法都是一样通用mysql语法. 不同点:DRDS有事务,,ADB无事务. 所以,数据源需要针对调用不同的接口来来进行切换. 整个处理过程,经历了比较坎坷的过程. 1.使用spring的切面+注解@DataSource来解决. 问题:在同一线程中抛出异常后,后续的异常处理方法,切换数据源失败. 2.使用注解+切面,在BO层进行处理. 问题:代码侵入性高,需要解决事务问题. 3.使用mybatis的多数据源,多MapperScan

Spring+Mybatis多数据源配置

一.配置文件 properties ds1.driverClassName=com.mysql.jdbc.Driver ds1.url=jdbc:mysql://192.168.200.130:3306/test1?useUnicode=true&characterEncoding=UTF-8 ds1.username=hhh ds1.password=123456 ds2.driverClassName=oracle.jdbc.OracleDriver ds2.url=jdbc:mysql:/