Spring3.2.1+Hibernate4.1.7 多数据源动态切换

时间:2022-08-14 19:38:48

             公司项目最近在整改,之前用spring jdbc 的数据链接现在要改成Hibernate,因为之前很少接触hibernate遇到的第一个问题就给难住了,配置多个SessionFactory显然是不符合规范 所以就想用Spring的多数据配置,在网上搜了很多资料所以记下来:

applicationContext-db.xml


<?xml version="1.0" encoding="UTF-8" ?>
<beans  xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">


<bean id="vids_bill_dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${bill.jdbc.driverClass}" />
<property name="jdbcUrl" value="${bill.jdbc.url}" />
<property name="user" value="${bill.jdbc.username}" />
<property name="password" value="${bill.jdbc.password}" />
<property name="maxPoolSize" value="${bill.jdbc.maxPoolSize}" />


<property name="minPoolSize" value="${c3p0.minPoolSize}" />
<property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}" />
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout}" />
<property name="initialPoolSize" value="${c3p0.minPoolSize}" />
<property name="maxIdleTime" value="${c3p0.maxIdleTime}" />
<property name="acquireIncrement" value="${c3p0.acquireIncrement}" />
<property name="maxIdleTimeExcessConnections" value="${c3p0.maxIdleTimeExcessConnections}" />
<property name="maxStatements" value="0" />
<property name="maxStatementsPerConnection" value="0" />


</bean>

<bean id="vids_bind_dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${bind.jdbc.driverClass}" />
<property name="jdbcUrl" value="${bind.jdbc.url}" />
<property name="user" value="${bind.jdbc.username}" />
<property name="password" value="${bind.jdbc.password}" />
<property name="maxPoolSize" value="${bind.jdbc.maxPoolSize}" />


<property name="minPoolSize" value="${c3p0.minPoolSize}" />
<property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}" />
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout}" />
<property name="initialPoolSize" value="${c3p0.minPoolSize}" />
<property name="maxIdleTime" value="${c3p0.maxIdleTime}" />
<property name="acquireIncrement" value="${c3p0.acquireIncrement}" />
<property name="maxIdleTimeExcessConnections" value="${c3p0.maxIdleTimeExcessConnections}" />
<property name="maxStatements" value="0" />
<property name="maxStatementsPerConnection" value="0" />


</bean>


    <bean id="dynamicDataSource" class="cn.com.hintsoft.configuration.DynamicDataSource">  
       <property name="targetDataSources">  
           <map key-type="java.lang.String">  
               <entry value-ref="vids_bill_dataSource" key="vids_bill_dataSource"></entry>  
               <entry value-ref="vids_bind_dataSource" key="vids_bind_dataSource"></entry>  
           </map>  
       </property>  
       <property name="defaultTargetDataSource" ref="vids_bind_dataSource"></property>  
   </bean>  
 
   <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
       <property name="dataSource" ref="dynamicDataSource" />  
       <property name="hibernateProperties">  
           <props>  
               <prop key="hibernate.dialect">${hibernate.dialect}</prop>  
               <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>  
               <prop key="hibernate.show_sql">true</prop>  
               <prop key="hibernate.format_sql">true</prop>  
               <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>  
           </props>  
       </property>  
       <property name="packagesToScan">  
           <list>  
               <value>cn.com.hintsoft.smsmanage.common.domain.*</value>  
           </list>  
       </property>  
   </bean>  
 
   <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
       <property name="sessionFactory" ref="sessionFactory" />  
   </bean>  
  <!-- 一定要注意事物的切入点:事物配置在哪一层数据切换的代码就写在那一层 -->
   <aop:config>  
       <aop:pointcut id="transactionPointCut" expression="execution(* cn.com.hintsoft.smsmanage.*.services.impl.*.*(..))" />  
       <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointCut" />  
   </aop:config>  
 
   <tx:advice id="txAdvice" transaction-manager="transactionManager">  
       <tx:attributes>  
           <tx:method name="add*" propagation="REQUIRED" />  
           <tx:method name="save*" propagation="REQUIRED" />  
           <tx:method name="update*" propagation="REQUIRED" />  
           <tx:method name="delete*" propagation="REQUIRED" />  
           <tx:method name="*" read-only="true" />  
       </tx:attributes>  
   </tx:advice>  
 
 <bean name = "basicDao" class = "cn.com.hintsoft.configuration.BasicDao" >
  <property name="sessionFactory" ref="sessionFactory"></property>
 </bean>
</beans>


DatabaseLocalHandler.java 

public class DatabaseLocalHandler {  

    private static final ThreadLocal<String> handler= new ThreadLocal<String>();  
  
    public static void setCustomerType(String customerType) {  
        handler.set(customerType);  
    }  
  
    public static String getCustomerType() {  
        return handler.get();
    }  
  
    public static void clearCustomerType() {  
        handler.remove();  
    }  
}  


DataSourceMap.java 常量存放

public class DataSourceMap {

public static final String VIDS_BILL_DATASOURCE = "vids_bill_dataSource";

public static final String VIDS_BIND_DATASOURCE = "vids_bind_dataSource";
}


DynamicDataSource.java 用于数据切换的类 继承了AbstractRoutingDataSource 这个类的源代码网上很多人都做了分析 有兴趣可以去查一下

public class DynamicDataSource extends AbstractRoutingDataSource{  
 
    @Override  
    protected Object determineCurrentLookupKey() {  
        return DatabaseLocalHandler.getCustomerType();   
    }  
  
}  


TestServiceImpl.java 演示  

@Service
public class TestServiceImpl implements TestService{


@Resource
TestDao testDao;

public void save(Object obj){
testDao.save(obj);
}

public void query(){
DatabaseLocalHandler.setCustomerType(DataSourceMap.VIDS_BILL_DATASOURCE); //注意这个位置代码的存放,事物必须配置到这个层 否则无法切换
testDao.query();

DatabaseLocalHandler.setCustomerType(DataSourceMap.VIDS_BIND_DATASOURCE); //切换到另一个数据库
testDao.query();
}
}


dao层的代码的话就不列举了,杂文一篇完成^.^