Hibernate 与 Spring 多数据源的配置

Spring2.0.1以后的版本已经支持配置 多数据源 ,并且可以在运行的时候动态加载不同的数据源。通过继承AbstractRoutingDataSource就可以实现 多数据源 的动态转换。

一、首先需要写一个静态的键值对照类:


代码
package cn.com.xinli.ccp.dynamicds;   
  
public class DataSourceMap {   
    public static final String Admin="Admin";   
    public static final String Yxh = "Yxh";   
}  
这个类主要在使用的时候当作获得数据源的标志使用。
二、建立一个获得和设置上下文的类:

代码
package cn.com.xinli.ccp.dynamicds;   
  
public class CustomerContextHolder {   
    private static final ThreadLocal contextHolder =   
        new ThreadLocal();   
       
    public static void setCustomerType(String customerType) {   
       contextHolder.set(customerType);   
     }   
       
    public static String getCustomerType() {   
      return (String) contextHolder.get();   
     }   
       
    public static void clearCustomerType() {   
       contextHolder.remove();   
     }   
  
}  

这个主要负责设置上下文环境和获得上下文环境。
三、建立动态数据源类,这个类必须继承AbstractRoutingDataSource:

代码
package cn.com.xinli.ccp.dynamicds;   
  
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;   
  
public class DynamicDataSource extends AbstractRoutingDataSource {   
  
    protected Object determineCurrentLookupKey() {   
        // TODO Auto-generated method stub   
        return CustomerContextHolder.getCustomerType();   
     }   
  
}  

这个类实现了 determineCurrentLookupKey方法,该方法返回一个Object,一般是返回字符串,也可以是枚举类型。该方法中直接使用了 CustomerContextHolder.getCustomerType()方法获得上下文环境并直接返回。
四、编写 spring 的配置文件配置数据源

代码
<bean id="parentDataSource"  
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
            <property name="driverClassName">  
                <value>COM.ibm.db2.jdbc.net.DB2Driver</value>  
            </property>  
            <property name="url">  
                <value>jdbc:db2:127.0.0.1:TEST</value>  
            </property>  
    </bean>  
       
    <bean id="adminDataSource" parent="parentDataSource">  
        <property name="username" value="admin"/>  
        <property name="password" value="master997mb"/>  
    </bean>  
       
    <bean id="yxhDataSource" parent="parentDataSource">  
        <property name="username" value="yxh"/>  
        <property name="password" value="yxh"/>  
    </bean>  

在 这个配置中可以看到首先有个parentDataSource,这个主要配置一些数据源的公用信息,项目中都是链接DB2数据库; adminDataSource和yxhDataSource是根据不同需要配置的个性化信息,但都必须加parent属性,值为 parentDataSource。这样就配置好了2个数据源信息。当然如果链接的 多数据源 是不同类型的两个数据库,那么parentDataSource就可以不要了,直接配置两个不同的数据源链接就可以了。
五、编写 spring 配置文件配置 多数据源 映射关系

代码
<bean id="dataSource" class="cn.com.xinli.ccp.dynamicds.DynamicDataSource">  
       <property name="targetDataSources">  
          <map key-type="java.lang.String">  
             <entry key="Yxh" value-ref="yxhDataSource"/>  
             <entry key="Admin" value-ref="adminDataSource"/> 
          </map>  
       </property>  
       <property name="defaultTargetDataSource" ref="adminDataSource"/>  
    </bean>  

在 这个配置中第一个property属性配置目标数据源,<map key-type="java.lang.String">中的key-type必须要和静态键值对照类DataSourceMap中的值的类型相 同;<entry key="Yxh" value-ref="yxhDataSource"/>中key的值必须要和静态键值对照类中的值相同,如果有多个值,可以配置多个< entry>标签。第二个property属性配置默认的数据源。
六、配置 hibernate 。
Hibernate 的配置和普通的 hibernate 、 spring 结合的配置一样

代码
<bean id="sessionFactory"  
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
        <!-- to override, use the "SpringDatasourceConfig" snippet in your project -->  
        <property name="dataSource">  
            <ref local="dataSource" />  
        </property>  
        <property name="mappingResources">  
            <list>  
                <value>  
                     cn/com/xinli/ccp/entity/User.hbm.xml   
                </value>  
                <value>  
                     cn/com/xinli/ccp/entity/Test.hbm.xml   
                </value>  
            </list>  
        </property>  
        <property name="hibernateProperties">  
            <props>  
                <prop key=" hibernate .dialect">  
                     org. hibernate .dialect.DB2Dialect   
                </prop>  
                   
                <prop key=" hibernate .show_sql">true</prop>  
                <prop key=" hibernate .use_outer_join">true</prop>  
                <prop key=" hibernate .jdbc.batch_size">50</prop>  
                <prop key=" hibernate .jdbc.fetch_size">5</prop>  
                <prop key=" hibernate .connection.pool_size">2</prop>  
                <prop key=" hibernate .connection.autocommit">false</prop>  
                <prop key=" hibernate .cache.use_query_cache">false</prop>  
                <prop key=" hibernate .max_fetch_depth">1</prop>  
                <prop key=" hibernate .bytecode.use_reflection_optimizer">true</prop>  
            </props>  
        </property>  
    </bean>  
  
<bean id="mydao" class="cn.com.xinli.ccp.dao.HibernateBaseDao">  
        <property name="sessionFactory">  
            <ref local="sessionFactory" />  
        </property>  
    </bean>  

关于dao的代码这里就省略了。
七、配置结束,可以使用了。

代码
public class DaoTest extends TestCase {   
  
    public void testSave() throws Exception{   
         CustomerContextHolder.setCustomerType(DataSourceMap.Admin);//设置数据源   
        // hibernate 创建实体   
         Test test = new Test();   
         test.setTest("22222222");   
           
         mydao.save(test);//使用dao保存实体   
           
         CustomerContextHolder.setCustomerType(DataSourceMap.Yxh);//设置为另一个数据源   
           
         mydao.save(test);//使用dao保存实体到另一个库中   
           
     }   
}  
在项目中对于编码人员对 多数据源 的切换可以做成透明的,操作同样的dao,就可以访问不同的数据库了。



猜你喜欢

转载自zhangkun716717-126-com.iteye.com/blog/1125498