设为首页 加入收藏

TOP

Spring+MyBatis多数据源切换
2015-11-12 21:29:19 】 浏览:7215
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 在普..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目