spring+mybatis多数据源切换

1.applicationContext.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">



 

2.具体实现切换的操作类:

/**
* @fileName DynamicDataSource.java
* @author chenkaideng
* @date 2015年8月27日
* @describe 动态获取数据源
*/
public class DynamicDataSource extends AbstractRoutingDataSource{
  @Override
  protected Object determineCurrentLookupKey() {
    // TODO Auto-generated method stub
    return DataSourceContextHolder.getDbType();
  }
}

 

/**
* @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(); 
  } 
}

 

 -》先是加载applicationContext.xml文件applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    -》然后设置数据源DataSourceContextHolder.setDbType("db1");
    -》接着从applicationContext 中获取sqlSession = (SqlSession) applicationContext.getBean("sqlSession");
    -》最后就可以拿这个sqlSession去做增删改查的操作
 
注意:不用对这个sqlSession做close和comit的操作,因为都已经由spring自己管理了,不用手动做这些操作。

你可能感兴趣的:(spring)