在仅使用ibatis时,多数据源简直就是梦魇,每多一个数据源就需要多一份sql-map-config配置文件。
e就可以简单的解决这个问题。
e实现了javax.sql.DataSource接口,因此可以理解为一个虚拟的动态DataSource,在需要的时候根据上下文Context动态决定使用哪个数据源。
下面是一个完整的配置:
1. beansxmlns="http://www.springframework.org/schema/beans"
2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3. xmlns:aop="http://www.springframework.org/schema/aop"
4. xmlns:tx="http://www.springframework.org/schema/tx"
5. xmlns:jee="http://www.springframework.org/schema/jee"
6. xsi:schemaLocation="
7. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
8. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
9. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
10. http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">
11.
12.
13.
14. <</span>jee:jndi-lookupid="ds0"jndi-name="jdbc/ds0"/>
15. <</span>jee:jndi-lookupid="ds1"jndi-name="jdbc/ds1"/>
16. <</span>jee:jndi-lookupid="ds2"jndi-name="jdbc/ds2"/>
17.
18. <</span>beanid="dataSource"class="com.xxx.xxx.util.DynamicDataSource">
19. <</span>propertyname="targetDataSources">
20. <</span>mapkey-type="java.lang.String">
21. <</span>entrykey="0"value-ref="ds0"/>
22. <</span>entrykey="1"value-ref="ds1"/>
23. <</span>entrykey="2"value-ref="ds2"/>
24. </</span>map>
25. </</span>property>
26. <</span>propertyname="defaultTargetDataSource"ref="1"/>
27. </</span>bean>
28.
29. <</span>beanid="sqlMapClient"class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
30. <</span>propertyname="dataSource"ref="dataSource"/>
31. <</span>propertyname="configLocation"value="classpath:com/xxx/xxx/dao/sqlmap/sql-map-config.xml"/>
32. </</span>bean>
33. <</span>beanid="testDAO"class="com.xxx.xxx.dao.impl.TestDAO">
34. <</span>propertyname="sqlMapClient"ref="sqlMapClient"/>
35. </</span>bean>
36. <</span>beanid="testService"class="com.xxx.xxx.service.impl.TestService">
37. <</span>propertyname="testDAO"ref="testDAO"/>
38. </</span>bean>
39. beans>
其核心是DynamicDataSource,代码如下
1. packagecom.xxx.xxx.util;
2.
3. importorg.apache.log4j.Logger;
4. importorg.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
5.
6. publicclassDynamicDataSource extendsAbstractRoutingDataSource {
7.
8. staticLogger log = Logger.getLogger("DynamicDataSource");
9. @Override
10. protectedObject determineCurrentLookupKey() {
11. // TODO Auto-generated method stub
12. returnDbContextHolder.getDbType();
13. }
14.
15.
上下文DbContextHolder为一线程安全的ThreadLocal,如下
1. packagecom.xxx.xxx.util;
2.
3. publicclassDbContextHolder {
4. privatestaticfinalThreadLocal contextHolder = newThreadLocal();
5.
6. publicstaticvoidsetDbType(String dbType) {
7. contextHolder.set(dbType);
8. }
9.
10. publicstaticString getDbType() {
11. return(String) contextHolder.get();
12. }
13.
14. publicstaticvoidclearDbType() {
15. contextHolder.remove();
16. }
17.
sql-map-config.xml如下