设为首页 加入收藏

TOP

Spring+MyBatis多数据源切换
2015-11-12 21:29:19 来源: 作者: 【 】 浏览:7
Tags:Spring MyBatis 数据源 切换

在实际的公司项目中,很可能会遇到一个问题就是,一个Java项目,但是项目中涉及两个数据库,这两个数据库还在不同IP的机子上。


遇到这种情况的时候,我们有两个选择


1、不走spring的aop方式,直接去多做两个dataSource


2、用spring进行管理,灵活地进行数据源切换


现在就来对第2种方式进行笔记:


spring.xml配置文件:


?
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
? ? http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
? ? http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
? ? http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-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/task http://www.springframework.org/schema/task/spring-task.xsd
? ? http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">?
?
? ? ?
? ?
? ?
? ?
? ? ? ? ? ? destroy-method="close">
? ? ? ?
? ? ? ?
? ? ? ?
? ? ? ?
? ? ? ?
? ?
? ? ?




? ?

? ?
? ? ? ? ? ? destroy-method="close">
? ? ? ?
? ? ? ?
? ? ? ?
? ? ? ?
? ? ? ?
? ?
? ? ?




? ?

? ?
? ?
? ? ? ?
? ? ? ? ? ?
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?
? ? ? ? ? ?

? ? ? ?

? ? ? ?
? ?

? ?
? ?
? ? ?







? ? ? ?
? ? ? ?



class="org.springframework.jdbc.datasource.DataSourceTransactionManager">


? ?


------------------------------------------------------------------


/**
?* @fileName DataSourceContextHolder.java
?* @author chenkaideng
?* @date 2015年8月27日
?* @describe 数据源设值Holder类
?*/
public class DataSourceContextHolder {
?
? private static final ThreadLocal contextHolder = new ThreadLocal();?
?
? public static void setDbType(String dbType) {?
? contextHolder.set(dbType);?
? }?
?
? public static String getDbType() {?
? return ((String) contextHolder.get());?
? }?
?
? public static void clearDbType() {?
? contextHolder.remove();?
? }?
}


弄完以上的事情,剩下的事情就简单了


-》先是加载spring.xml文件applicationContext = new ClassPathXmlApplicationContext("spring.xml");


-》然后设置数据源DataSourceContextHolder.setDbType("db1");


-》接着从applicationContext 中获取sqlSession = (SqlSession) applicationContext.getBean("sqlSession");


-》最后就可以拿这个sqlSession去做增删改查的操作


注意:不用对这个sqlSession做close和comit的操作,因为都已经由spring自己管理了,不用手动做这些操作。


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇MySQL与MariaDB 新型主从集群配置.. 下一篇MariaDB 10.1 和 MySQL 5.7 在普..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·【超详细】JDK 下载 (2025-12-24 18:19:32)
·Java_百度百科 (2025-12-24 18:19:29)
·简介 - Java教程 - (2025-12-24 18:19:27)
·C++ 语言社区-CSDN社 (2025-12-24 17:48:24)
·CSDN问答专区社区-CS (2025-12-24 17:48:22)