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.执行结果例如以下图:
以上数据库分库已经大功告成,以后在与大家具体介绍怎样分表。以及分表的原则。
文章中如有错误,欢迎高手指正,本人是一个小菜鸟。正在努力学习中。
Spring+MyBatis双数据库配置的更多相关文章
- spring,mybatis事务管理配置与@Transactional注解使用[转]
spring,mybatis事务管理配置与@Transactional注解使用[转] spring,mybatis事务管理配置与@Transactional注解使用 概述事务管理对于企业应用来说是至关 ...
- spring,mybatis事务管理配置与@Transactional注解使用
spring,mybatis事务管理配置与@Transactional注解使用[转] spring,mybatis事务管理配置与@Transactional注解使用 概述事务管理对于企业应用来说是 ...
- Spring+MyBatis实践—工程配置
初次实践:Spring+MyBatis技术搭建框架,采用Bootstrap前端开源框架. 简介: MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis 消除 了几乎所 ...
- Spring+MyBatis实现数据库读写分离方案
推荐第四种:https://github.com/shawntime/shawn-rwdb 方案1 通过MyBatis配置文件创建读写分离两个DataSource,每个SqlSessionFactor ...
- MyBatis中---数据库配置的属性名冲突问题
一.db.properties 属性文件中 最好加特殊的标志前缀 jdbc.username ,如果单纯的username有可能影响到 mapper.xml中的 ${username}; 举例 ...
- mysql+spring+mybatis实现数据库读写分离[代码配置] .
场景:一个读数据源一个读写数据源. 原理:借助spring的[org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource] ...
- 使用IDEA的gradle整合spring+ mybatis 采用javaconfig配置
1.新建一个工程 2.工程目录 3.添加gradle.propertes文件 activeMQVersion=5.7.0 aspectJVersion=1.7.2 commonsLangVersion ...
- spring+mybatis的简单配置示例
简单代码结构: //Book.java package com.hts.entity; public class Book { private String id; private String bo ...
- spring mybatis 多数据源配置
1.创建好数据库的配置文件 mysql.url=jdbc:mysql://***/***?useUnicode=true&characterEncoding=UTF-8 mysql.usern ...
随机推荐
- android 更新ui
https://www.cnblogs.com/rayray/p/3437048.html https://www.cnblogs.com/zhaoyanjun/p/5546683.html
- LDA解决的问题
人类是怎么生成文档的呢?LDA的这三位作者在原始论文中给了一个简单的例子.比如假设事先给定了这几个主题:Arts.Budgets.Children.Education,然后通过学习训练,获取每个主题T ...
- VUEJS2.0源码理解--优
VUEJS2.0源码理解 http://jiongks.name/blog/vue-code-review/#pingback-112428
- PIE加载自定义服务数据详细介绍
这段时间我一直在研究如何用PIE加载在线地图服务,遇到了许多问题,多亏了技术员小姐姐的帮助,才让我能正确加载ArcGIS Online在线服务.天地图在线地图和谷歌在线地图.我是根据博客园PIE官方博 ...
- 应用MVP模式对遗留代码进行重构
AV(Autonomous View)自治视图 在面向终端用户的应用中,都需要一个可视化的UI来与用户交互.这个UI称为View视图. 在早期,我们习惯将所有前台的逻辑,与视图揉在一起,称为AV自治视 ...
- 洛谷P2391 白雪皑皑(并查集)
题目背景 “柴门闻犬吠,风雪夜归人”,冬天,不期而至.千里冰封,万里雪飘.空中刮起了鸭毛大雪.雪花纷纷,降落人间. 美能量星球(pty 在 spore 上的一个殖民地)上的人们被这美景所震撼.但是 p ...
- Git Learning Part I - Install Git and configure it
Why we need 'Git' GIt version control: 1. record the history about updating code and deleting code 2 ...
- DB2 char长度问题
问题:发现用char转换了后的值长度都变为了11,更长的变为了254
- DDoS攻击与防范策略
DDoS(Distributed Denial of Service,分布式拒绝服务)攻击的主要目的是让指定目标无法提供正常服务,甚至从互联网上消失,是目前最强大.最难防御的攻击之一. 按照发起的方式 ...
- swift的计算属性和懒加载
计算属性每次都重新计算. 懒加载只计算一次. 可以借助backing store将计算属性转化为懒加载属性. 计算属性实质上退化为函数调用. 计算属性的标示是get.set.