2011-10-10 68 views

回答

5

我相信Spring中可以有多個SessionFactory,每個SessionFactor都使用一個單獨的DataSource。您可以將特定的SessionFactory傳遞給適當的DAO。

3

如果您在out spring中使用hibernate,您可以爲每個數據庫設置多個hibernate屬性xml。在這些xml文件中,您可以指定數據庫主機,用戶名,密碼,數據庫名稱和其他連接屬性。您可以使用xml文件創建多個會話工廠,並在DAO類中使用正確的會話工廠。

1

創建一個包含HibernateProperties和SessionFactory實體的類。 喜歡的東西:

public class HibernateSessionFactory { 
     private static final long serialVersionUID = 1L; 

     private static Log log = LogFactory.getLog(HibernateSessionFactory.class); 

     private Resource[] mappingLocations; 

     private Properties hibernateProperties; 

     private SessionFactory factory; 

這將是很好,如果你可以在以後使用Spring,並與數據庫連接的詳細注入這個類的,後來這個HibernateSessionFactory分配給相關的DAO類。

我以前做過,或多或少它看起來像這樣:

<bean id="mapHibernateFactory" 
       class="com.geofencing.dao.hibernate.HibernateSessionFactory" 
       init-method="init" destroy-method="dispose" scope="singleton"> 
       <property name="mappingResources"> 
         <list> 
           ..... your hibernate mapping files ..... 
         </list> 
       </property> 
       <property name="hibernateProperties"> 
         <props> 
           <prop key="hibernate.hbm2ddl.auto">false</prop> 
           <prop key="hibernate.show_sql">false</prop> 
           <prop key="hibernate.format_sql">false</prop> 
           <prop key="hibernate.connection.isolation">4</prop> 
           <prop key="hibernate.connection.autocommit">false</prop> 
           <prop key="hibernate.connection.url">${jdbc.url}</prop> 
           <prop key="hibernate.connection.username">${jdbc.username}</prop> 
           <prop key="hibernate.connection.password">${jdbc.password}</prop> 
           <prop key="hibernate.connection.driver_class">${jdbc.driverClassName}</prop> 
           <prop key="hibernate.dialect">${jdbc.dialect}</prop> 
           <prop key="hibernate.c3p0.min_size">5</prop> 
           <prop key="hibernate.c3p0.max_size">20</prop> 
           <prop key="hibernate.c3p0.timeout">1800</prop> 
           <prop key="hibernate.c3p0.max_statements">50</prop> 
           <prop key="hibernate.cache.provider_class"> org.hibernate.cache.EhCacheProvider</prop> 
           <prop key="net.sf.ehcache.configurationResourceName">WEB-INF/ehcache.xml</prop> 
           <prop key="hibernate.cglib.use_reflection_optimizer">false</prop> 
           <prop key="hibernate.connection.zeroDateTimeBehavior">convertToNull</prop> 
           <prop key="hibernate.connection.autoReconnect">true</prop> 
           <prop key="hibernate.connection.autoReconnectForPools">true</prop> 
         </props> 
       </property> 
     </bean> 

不知道如何與註解做到這一點,雖然。