使用多数据源的场景应该是很多的,如操作同一台服务器上不同的数据库,或者多地机器上的相同或不相同数据库。

  虽然涉及到不同数据库时,我们也许可以通过跨库操作的方式,如 other.user 使用同一数据源来操作数据库,但是,这样明显使得应用很难扩展,单数据库将无法拆离。使用多数据源操作则可以解决这个问题。

  在spring中怎样使用多数据源?本文通过实践方式,让我配置多数据源有个参考。(不得不说,java中很大的一个难点就在于配置环境)

  从入口处更改,web.xml中添加引用spring配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>c</display-name>
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- URL重写 -->
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping> <servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping> <display-name>c</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list> <filter>
<filter-name>JAMonFilter</filter-name>
<filter-class>com.xx.core.web.filter.PageMonFilter</filter-class>
<init-param>
<param-name>flag</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>JAMonFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>exceptions</servlet-name>
<jsp-file>/jamon/exceptions.jsp</jsp-file>
</servlet>
<servlet>
</web-app>

2. 在application.xml中添加多数据源配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="
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/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.5.xsd"> <bean class="com.xx.c.common.utils.SpringContextsUtil" />
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="driverClassName" value="${jdbc.driver}" />
<property name="maxActive" value="${pool.maxPoolSize}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 超过时间限制是否回收 -->
<property name="removeAbandoned" value="true" />
<!-- 超时时间;单位为秒。180秒=3分钟 -->
<property name="removeAbandonedTimeout" value="${pool.removeAbandonedTimeout}" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="${pool.maxWait}" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="${pool.timeBetweenEvictionRunsMillis}" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="${pool.minEvictableIdleTimeMillis}" />
<property name="validationQuery" value="${pool.validationQuery} " />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
</bean>
<bean id="dataSource_c" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="url" value="${jdbc2.url}" />
<property name="driverClassName" value="${jdbc2.driver}" />
<property name="maxActive" value="${pool2.maxPoolSize}" />
<property name="username" value="${jdbc2.username}" />
<property name="password" value="${jdbc2.password}" />
<property name="removeAbandoned" value="true" />
<property name="removeAbandonedTimeout" value="${pool2.removeAbandonedTimeout}" />
<property name="maxWait" value="${pool2.maxWait}" />
<property name="timeBetweenEvictionRunsMillis" value="${pool2.timeBetweenEvictionRunsMillis}" />
<property name="minEvictableIdleTimeMillis" value="${pool2.minEvictableIdleTimeMillis}" />
<property name="validationQuery" value="${pool2.validationQuery} " />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
</bean>
<context:component-scan base-package="com.xx.c">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<context:component-scan base-package="com.xx.c.pojo.config" />
<bean class="com.xx.framework.web.v1_0_0.ServerController" /> <!-- spring的属性加载器,加载properties文件中的属性 -->
<bean class="com.xx.zkc.property.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>classpath*:/spring/conf.properties</value>
</list>
</property>
</bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean>
<bean id="sqlSessionFactory_c" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource_c" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"
scope="prototype">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<bean id="sqlSession_c" class="org.mybatis.spring.SqlSessionTemplate"
scope="prototype">
<constructor-arg index="0" ref="sqlSessionFactory_c" />
</bean> <mongo:mongo id="mongo" replica-set="${mongodb.url}">
<mongo:options connections-per-host="${mongo.connections.per.host}"
threads-allowed-to-block-for-connection-multiplier="${mongo.threads.allowed.to.block.for.connection.multiplier}"
connect-timeout="${mongo.connect.timeout}" max-wait-time="${mongo.max.wait.time}"
auto-connect-retry="${mongo.auto.connect.retry}" socket-keep-alive="${mongo.socket.keep.alive}"
socket-timeout="${mongo.socket.timeout}" slave-ok="${mongo.slave.ok}"
write-number="${mongo.write.number}" write-timeout="${mongo.write.timeout}"
write-fsync="${mongo.write.fsync}" />
</mongo:mongo>
<bean id="mappingContext"
class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" />
<bean id="defaultMongoTypeMapper"
class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">
<constructor-arg name="typeKey">
<null />
</constructor-arg>
</bean>
<bean id="mongoDbFactory"
class="org.springframework.data.mongodb.core.SimpleMongoDbFactory">
<constructor-arg ref="mongo" />
<constructor-arg name="databaseName" value="${mongodb.databaseName}" />
</bean> <bean id="mappingMongoConverter"
class="org.springframework.data.mongodb.core.convert.MappingMongoConverter">
<constructor-arg name="mappingContext" ref="mappingContext" />
<property name="typeMapper" ref="defaultMongoTypeMapper" />
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean> <bean id="mongodbReadPreference" class="com.mongodb.ReadPreference"
factory-method="secondaryPreferred" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<property name="readPreference" ref="mongodbReadPreference" />
<constructor-arg name="mongoConverter" ref="mappingMongoConverter" />
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean> <!-- 事务 控制 begin -->
<bean name="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 事务 控制 end --> <!-- action begin -->
<bean name='requestMappingHandlerMapping'
class='com.xx.core.web.spring.annotation.PackageURLRequestMappingHandlerMapping'>
<property name='packageBase' value='com.xx.c.action'></property>
<property name="interceptors">
<list>
<bean class="com.xx.core.web.spring.interceptor.SessionInterceptor">
<property name="on" value="${system.check.permission}" />
<property name="sessionTimeout" value="${system.timeout}" />
<property name="userSessionDao" ref="userSessionDao" />
<property name="systemDao" ref="systemDao" />
</bean>
</list>
</property>
</bean> <!-- dao -->
<import resource="dao.xml" /> <!-- service -->
<import resource="service.xml" /> <!-- activemq -->
<import resource="applicationContext-activemq.xml" /> <!-- redis -->
<import resource="applicationContext-redis.xml" /> <!-- dubbo -->
<import resource="applicationContext-dubbo.xml" />
<import resource="applicationContext-dubbo-consumer.xml" /> <import resource="classpath:spring/xx-c-kafka-consumer.xml" /> <import resource="applicationContext-rabbitmq-producer.xml"/> <import resource="applicationContext-rabbitmq-consumer.xml"/> <bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="com.xx.core.web.spring.convert.JSONHttpMessageConverter">
</bean>
<bean
class="org.springframework.http.converter.StringHttpMessageConverter">
</bean>
<bean
class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
</bean>
<bean
class="org.springframework.http.converter.xml.SourceHttpMessageConverter">
</bean>
<bean
class="org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter">
</bean>
</list>
</property>
<property name="customArgumentResolvers">
<list>
<bean class="com.xx.core.web.spring.bind.TIDArgumentResolver" />
<bean
class="com.xx.core.web.spring.bind.RequestAttributeArgumentResolver" />
<bean class="com.xx.core.web.spring.bind.ClientIPArgumentResolver" />
<bean
class="com.xx.core.web.spring.bind.SessionUserIdArgumentResolver" />
</list>
</property>
</bean> <bean id="dealException" class="com.xx.core.web.spring.interceptor.ExceptionAop"></bean>
<aop:config>
<!-- 对异常的集中处理 -->
<aop:aspect id="exceptionAop" ref="dealException">
<aop:pointcut id="exceptionPointCut"
expression="execution(* com.xx.c.action.*.*.*(..))" />
<aop:around pointcut-ref="exceptionPointCut" method="deal" />
</aop:aspect>
</aop:config> <bean
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
<value>systemDictDao</value>
<value>userDao</value>
<value>infoDao</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>jamonInterceptor</value>
</list>
</property>
</bean>
<bean id="jamonInterceptor"
class="org.springframework.aop.interceptor.JamonPerformanceMonitorInterceptor"></bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="utf-8" p:maxUploadSize="104857600" />
<context:component-scan base-package="com.xx.c.action"
name-generator="com.xx.core.web.spring.annotation.FullPackageBeanNameGenerator" />
<!-- action end -->
<!-- Spring托管线程池 -->
<bean id="threadPoolTaskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- 线程池活跃的线程数 -->
<property name="corePoolSize" value="50" />
<!-- 线程池最大活跃的线程数 -->
<property name="maxPoolSize" value="75" />
<!-- 队列的最大容量 <property name ="queueCapacity" value ="2000" /> -->
<!-- <property name="WaitForTasksToCompleteOnShutdown" value="true" /> -->
</bean> <bean id="mapper" class="org.dozer.spring.DozerBeanMapperFactoryBean">
<property name="mappingFiles">
<list>
<value>classpath:/dozerBeanMapping.xml</value>
<value>classpath:/dozerBeanMapping2.xml</value>
</list>
</property>
</bean> </beans>

3. 在dao.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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<!-- import this -->
<bean id="userDao" class="com.xx.c.dao.user.UserDaoImpl">
<property name="sqlSession" ref="sqlSession" />
<property name="mongoTemplate" ref ="mongoTemplate" />
</bean> <bean id="infoDao" class="com.xx.c.dao.content.ConInfoDaoImpl">
<property name="sqlSession" ref="sqlSession_c" />
</bean>
</beans>

4. 在具体的sql当中实现数据操作:

<?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.xx.c.dao.user.UserDao">
<resultMap id="userMap" type="User">
<id column="user_id" property="userId" />
<result column="username" property="userName" />
<result column="sex" property="sex" />
</resultMap>
<resultMap id="userInfoMap" type="UserInfoBean">
<id column="user_id" property="userId" />
<result column="card_id" property="cardId" />
<result column="username" property="phone" />
<result column="id_card_address" property="idCardAddress" />
<result column="reg_time" property="regTime" />
<result column="logintime" property="logintime" />
<result column="last_time" property="lastTime" />
<result column="reg_ip" property="regIp" />
<result column="up_ip" property="upIp" />
<result column="last_ip" property="lastIp" />
<result column="download_channel" property="downloadChannel" /> <result column="guarantor1" property="guarantor1" />
<result column="guarantor_phone1" property="guarantor_phone1" />
</resultMap> <sql id="getUserCond">
<where>
<if test="userId != null">
and u.user_id = #{userId}
</if>
<if test="userName != null and userName != ''">
and u.username = #{userName}
</if>
</where>
</sql> <select id="getUser" resultMap="userMap" parameterType="User">
select u.* from users_info u
<include refid="getUserCond" />
</select> <insert id="addDebitCardBindChannel" parameterType="DebitCardBindChannelBean">
insert into
nzz (
user_id,channel,
card_no,request_id,status)
values (
#{userId},#{channel},#{cardNo},#{requestId},#{status})
</insert> <update id="updateDebitCardBindChannel" parameterType="DebitCardBindChannelBean">
update
nzz
set status=#{status}
,request_id=#{requestId}
where
user_id=#{userId} and card_no=#{cardNo}
and channel=#{channel}
</update>
</mapper>

5. 完善一下,使用别名,使sql写的时候更简短:

<?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="logPrefix" value="dao."/>
</settings>
<!-- 配置别名,以便在引用时简写 -->
<typeAliases>
<typeAlias alias="User" type="com.xx.c.pojo.user.User" />
<typeAlias alias="CardBinBean" type="com.xx.c.pojo.user.CardBinBean"/>
<typeAlias alias="UserCreditLogBean" type="com.xx.c.pojo.user.UserCreditLogBean"/>
<typeAlias alias="InfoBean" type="com.xx.c.pojo.content.ContentInfo" />
</typeAliases> <mappers>
<mapper resource="com/xx/c/dao/impl/User.xml"/>
<mapper resource="com/xx/c/dao/impl/Info.xml"/>
</mappers> </configuration>

以上,就已经完成了一整个spring操作多数据源的mybatis了。

如何使用spring配合mybatis配置多个数据源并应用?的更多相关文章

  1. spring集成mybatis配置多个数据源,通过aop自动切换

    spring集成mybatis,配置多个数据源并自动切换. spring-mybatis.xml如下: <?xml version="1.0" encoding=" ...

  2. Spring Boot + Mybatis 配置多数据源

    Spring Boot + Mybatis 配置多数据源 Mybatis拦截器,字段名大写转小写 package com.sgcc.tysj.s.common.mybatis; import java ...

  3. spring mvc+myBatis配置详解

    一.spring mvc Spring框架(框架即:编程注解+xml配置的方式)MVC是Spring框架的一大特征,Spring框架有三大特征(IOC(依赖注入),AOP(面向切面),MVC(建模M- ...

  4. Spring Boot MyBatis配置多种数据库

    mybatis-config.xml是支持配置多种数据库的,本文将介绍在Spring Boot中使用配置类来配置. 1. 配置application.yml # mybatis配置 mybatis: ...

  5. Spring Boot + Mybatis多数据源和动态数据源配置

    文章转自 https://blog.csdn.net/neosmith/article/details/61202084 网上的文章基本上都是只有多数据源或只有动态数据源,而最近的项目需要同时使用两种 ...

  6. Spring SpringMVC MyBatis配置笔记

    工程大致结构: project |-src |----pojo |--------Temp.java |----dao |--------TempDao.java |--------TempDao.x ...

  7. spring 、Mybatis配置sql server数据库

    学习了:http://www.cnblogs.com/amwicfai/p/3181003.html beans.xml中的配置写法: <!-- 数据源 --> <bean id=& ...

  8. maven 构建spring ssh mybatis 配置

    详情参与 http://blog.csdn.net/yuguiyang1990/article/details/8811817 前面我们使用Maven构建了Struts2项目,这里我们来试一下Hibe ...

  9. spring+mybatis配置多个数据源

    http://www.cnblogs.com/lzrabbit/p/3750803.html

随机推荐

  1. vue项目中使用axios上传图片等文件

    form表单提交图片会刷新页面,也可以时form绑定到一个隐藏的iframe上,可以实现无刷新提交数据. html代码: <input name="file" type=&q ...

  2. day43 多表查询和pymysql

    复习 增删改查全语法 # 增 insert into db1.t1(字段2, 字段1, ..., 字段n)|省略 values (值2, 值1, ..., 值n)|(值1, 值2, ..., 值n)[ ...

  3. 【Django】网页跳转的问题

    这两天有个比较奇怪了问题困扰着我,就是网页跳转之后页面没有变化,虽然url已经变了,但是页面还是原来的,只是表单数据清空了 就是http://127.0.0.1:8000/signup_signin/ ...

  4. Windows server 2012 R2 解决“无法完成域加入,原因是试图加入的域的SID与本计算机的SID相同

    Windows server 2012 R2 解决“无法完成域加入,原因是试图加入的域的SID与本计算机的SID相同.”使用克隆的系统时,加域是出现如下问题.“无法完成域加入,原因是试图加入的域的SI ...

  5. c++ 面试题(网络类)

    1,若服务器方单独终止之后,客户端继续发数据会怎么样? https://blog.csdn.net/Nick_666/article/details/78342442 https://www.zhih ...

  6. Demo002 IDEA中Junit单元测试的使用(初级篇)

    推荐JUnit视频教程:JUnit-Java单元测试必备工具. 1.基本理论 1.1 单元测试 单元测试又称模块测试,属于白盒测试,是最小单位的测试.模块分为程序模块和功能模块.功能模块指实现了一个完 ...

  7. easyui的datagrid改变单元格颜色

    另一种方法:https://www.cnblogs.com/raitorei/p/10395233.html easyui的datagrid改变整行颜色:https://www.cnblogs.com ...

  8. SQL Server 2000使用链接服务器

    执行:安装盘\SQL2KSP4\install\instcat.sql 文件下载地址:http://download.csdn.net/detail/taomanman/5680765

  9. 设置angular公共样式表

    一.现象 新创建的项目,是直接显示在src目录下的,假如会用到其它第三方的全局样式时,不能统一放在一个地方统一来管理,就会感觉有点乱. 二.解决 1.移动样式表. 在assets文件夹(该文件夹一般都 ...

  10. 面试01:解释内存中的栈(stack)、堆(heap)和方法区(method area)的用法

    栈的使用:通常我们定义一个基本数据类型的变量,一个对象的引用,还有就是函数调用的现场保存都使用JVM中的栈空间. 队的使用:通过new关键字和构造器创建的对象则放在堆空间,堆是垃圾收集器管理的主要区域 ...