iBatis多数据源的苦恼
在仅使用ibatis时多数据源简直就是梦魇每多一个数据源就需要多一份sqlmapconfig配置文件
采用spring的AbstractRoutingDataSource就可以简单的解决这个问题
AbstractRoutingDataSource实现了javaxsqlDataSource接口因此可以理解为一个虚拟的动态DataSource在需要的时候根据上下文Context动态决定使用哪个数据源
Spring+iBatis多数据源的配置
下面是一个完整的配置
< beans xmlns=
xmlns:xsi=instance
xmlns:aop=
xmlns:tx=
xmlns:jee=
xsi:schemaLocation=
beansxsd
aopxsd
txxsd
jeexsd>
< ! ========================= GENERAL DEFINITIONS ========================= >
< jee:jndilookup id=ds jndiname=jdbc/ds/>
< jee:jndilookup id=ds jndiname=jdbc/ds/>
< jee:jndilookup id=ds jndiname=jdbc/ds/>
< bean id=dataSource class=comxxxxxxutilDynamicDataSource>
< property name=targetDataSources>
< map keytype=javalangString>
< entry key= valueref=ds/>
< entry key= valueref=ds/>
< entry key= valueref=ds/>
< /map>
< /property>
< property name=defaultTargetDataSource ref=/>
< /bean>
< ! SqlMap setup for iBATIS Database Layer >
< bean id=sqlMapClient class=orgspringframeworkormibatisSqlMapClientFactoryBean>
< property name=dataSource ref=dataSource/>
< property name=configLocation value=classpath:com/xxx/xxx/dao/sqlmap/sqlmapconfigxml/>
< /bean>
< bean id=testDAO class=comxxxxxxdaoimplTestDAO>
< property name=sqlMapClient ref=sqlMapClient/>
< /bean>
< bean id=testService class=comxxxxxxserviceimplTestService>
< property name=testDAO ref=testDAO/>
< /bean>
< /beans>
其核心是DynamicDataSource代码如下
package comxxxxxxutil;
import orgapachelogjLogger;
import orgspringframeworkjdbcdatasourcelookupAbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
static Logger log = LoggergetLogger(DynamicDataSource);
@Override
protected Object determineCurrentLookupKey() {
// TODO Autogenerated method stub
return DbContextHoldergetDbType();
}
}
上下文DbContextHolder为一线程安全的ThreadLocal如下
package comxxxxxxutil;
public class DbContextHolder {
private static final ThreadLocal contextHolder = new ThreadLocal();
public static void setDbType(String dbType) {
contextHolderset(dbType);
}
public static String getDbType() {
return (String) contextHolderget();
}
public static void clearDbType() {
contextHolderremove();
}
}
sqlmapconfigxml如下
< ?xml version= encoding=UTF standalone=no?>
< !DOCTYPE sqlMapConfig PUBLIC ////DTD SQL Map Config //EN
mapconfigdtd>
< sqlMapConfig>
< sqlMap resource=com/xxx/xxx/dao/sqlmap/Objectxml/>
< /sqlMapConfig>
这样在调用service之前只需要设置一下上下文即可调用相应的数据源如下
DbContextHoldersetDbType();
//execute services
//
dao如下
package comxxxxxxdaoimpl;
import javautilHashMap;
import javautilList;
import javautilMap;
import orgapachelogjLogger;
import orgspringframeworkormibatissupportSqlMapClientDaoSupport;
import comxxxxxxvoTestObj;
public class TestDAO extends SqlMapClientDaoSupport implements ITestDAO {
static Logger log = LoggergetLogger(TestDAOclass);
public TestObj getTestObj(String objID) throws Exception {
return (TestObj) getSqlMapClientTemplate()queryForObject(getTestObj objID);
}
}
以上就介绍了Spring+iBatis多数据源的配置方案本文来自eddysheng的博客《基于spring和ibatis的多数据源切换方案》