如何使用带有 Spring 和 Hibernate 的会话工厂处理多个数据库连接

IT小君   2022-11-09T23:46:55

我对 Hibernate 真的很陌生,现在一直在考虑一些事情。我有两个数据库,我在 Tomcat 的 context.xml 中定义了 JNDI 连接字符串。在我使用 Spring 和 Hibernate 的应用程序中,我有 2 个会话工厂,第一个如下 ->

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="hibernateProperties">
  <props>
    <prop key="hibernate.hbm2ddl.auto">update</prop>
    <prop key="hibernate.connection.pool_size">10</prop>
    <prop key="hibernate.show_sql">true</prop>
    <prop key="hibernate.transaction.auto_close_session">true</prop>
    <prop key="hibernate.transaction.flush_before_completion">true</prop>
    <prop key="current_session_context_class">true</prop>

    <!--HSQL-->
    <prop key="hibernate.connection.datasource">java:comp/env/jdbc/xxx</prop>
    <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
    <prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>

  </props>
</property>
<property name="annotatedClasses">
  <list>
    <value>com.mytest.examples.Person</value>
    <value>com.mytest.examples.Customer</value>
    <value>com.mytest.examples.Employee</value>
  </list>
</property>

第二个 sessionFactory 指向第二个数据库如下

<bean id="sessionFactory2" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="hibernateProperties">
  <props>
    <prop key="hibernate.hbm2ddl.auto">update</prop>
    <prop key="hibernate.connection.pool_size">10</prop>
    <prop key="hibernate.show_sql">true</prop>
    <prop key="hibernate.transaction.auto_close_session">true</prop>
    <prop key="hibernate.transaction.flush_before_completion">true</prop>
    <prop key="current_session_context_class">true</prop>

    <!--HSQL-->
    <prop key="hibernate.connection.datasource">java:comp/env/jdbc/yzz</prop>
    <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
    <prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>

  </props>
</property>
<property name="annotatedClasses">
  <list>
    <value>com.mytest.examples.Container</value>
    <value>com.mytest.examples.Credentials</value>
  </list>
</property>

现在,当我尝试使用以下这些工厂时

Session session = getHibernateTemplate().getSessionFactory().openSession();

默认情况下,我总是获得第一个工厂,并且能够访问其架构中的所有表,但不能访问第二个工厂。如何指定要使用的工厂?

点击广告,支持我们为你提供更好的服务
评论(1)
IT小君

构造HibernateTemplate函数接受一个SessionFactory作为参数。我不知道getHibernateTemplate()您的代码中做了什么,但它应该返回一个HibernateTemplate使用您定义的 SessionFactory bean 之一构建的(通过在 spring 上下文 xml 文件中声明它们,或者通过从注入的会话工厂之一用 Java 构建它们) )。

请注意,正如 HibernateTemplate 的文档所说(粗体):

从 Hibernate 3.0.1 开始,事务性 Hibernate 访问代码也可以用普通的 Hibernate 样式编码。因此,对于新开始的项目,请考虑采用基于 SessionFactory.getCurrentSession() 的标准 Hibernate3 编码数据访问对象的风格。

我会直接注入会话工厂,并直接使用 Hibernate API。HibernateTemplate 并没有带来太多的 Hibernate API 并且经常妨碍,恕我直言。(例如,不提供 的等价物Query.uniqueResult())。

2022-11-09T23:46:55   回复