如果无法处理多个数据源,hibernate可以使用多个sessionFactory

时间:2014-05-08 08:14:42

标签: hibernate

我遇到了一个问题,如何在baseDao中处理多个sessionFactory?

public class BaseDao<T> extends HibernateDaoSupport implements IBaseDao<T> {


//注入SessionFactory
@Resource(name="sessionFactory")
public void setSuperSessionFactory(SessionFactory sessionFactory){
    super.setSessionFactory(sessionFactory);
}

@Resource(name="secondSessionFactory")
public void setSuper2SessionFactory(SessionFactory secondSessionFactory){
    super.setSessionFactory(secondSessionFactory);
}

1 个答案:

答案 0 :(得分:0)

创建不同会话工厂的一个方法是使用不同的* .cfg.xml * .cfg.xml配置文件。然后使用

Configuration con = new Configuration().configure("*.cfg.xml");     

在XML文件中使用以下代码

 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
       destroy-method="close"   
       driverClassName="***"
       url="jdbc:sqlserver://${FirstDB_HosName}
          \${FirstDB_instanceName}:${FirstDB_PortNumber};databaseName= 
           ${FirstDB_DatabaseName}; username=${FirstDB_UserName}; 
           password=${FirstDB_Password};" />
  <bean id="sessionFactory" 
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
     <property name="dataSource" ref="dataSource" />
     <property name="configLocation">
       <value>classpath:hibernate.cfg.xml</value>
     </property>
     <property name="hibernateProperties">
       <props>  
         <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
         <prop key="hibernate.current_session_context_class">thread</prop>
         <prop key="show_sql">false</prop>
       </props>
    </property>   
</bean>     


<bean id="seconddataSource" class="org.apache.commons.dbcp.BasicDataSource"
       destroy-method="close"   
       driverClassName="***"
       url="jdbc:sqlserver://${SecondDB_HosName}
          \${SecondDB_instanceName}:${SecondDB_PortNumber};databaseName= 
           ${SecondDB_DatabaseName}; username=${SecondDB_UserName}; 
           password=${SecondDB_Password};" />
  <bean id="secondsessionFactory" 
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
     <property name="dataSource" ref="seconddataSource" />
     <property name="configLocation">
       <value>classpath:hibernate-second.cfg.xml</value>
     </property>
     <property name="hibernateProperties">
       <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
         <prop key="hibernate.current_session_context_class">thread</prop>
         <prop key="show_sql">false</prop>
       </props>
    </property>
</bean>

在DAO中,使用@Qualifier注释连接2个会话工厂

@Autowired
@Qualifier(value="sessionFactory")
private SessionFactory sessionFactory;  

@Autowired
@Qualifier(value="secondDBSessionFactory")
private SessionFactory SecondSessionFactory;