【问题标题】:How to access hibernate session via AnnotationSessionFactoryBean?如何通过 AnnotationSessionFactoryBean 访问休眠会话?
【发布时间】:2011-09-12 14:10:24
【问题描述】:

我想把hibernate和spring结合起来。 spring 3 文档说您可以通过 org.hiberate.SessionFactory 的 getCurrentSession() 访问会话,这应该优于 hibernateDaoSupport 方法。

但是我想知道,如果我们使用 AnnotationSessionFactoryBean,我们首先如何获取 org.hiberate.SessionFactory 的实例? 我在 applicationContext.xml 中做了以下 bean 声明:

       <bean id="annotationSessionFactoryBean" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
              <property name="dataSource" ref="dataSource"/>
              <property name="packagesToScan" value="com.mydomain"/>
              <property name="hibernateProperties">
                  <props>
                    <prop key="hibernate.connection.pool_size">10</prop>
                    <prop key="hibernate.connection.show_sql">true</prop>
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                  </props>
            </property>     
    </bean>

正在使用会话的 DAO:

    <bean id="hibernateUserProfileDAO" class="com.springheatmvn.Dao.impl.hibernate.HibernateUserProfileDAO">
        <property name="annotationSessionFactoryBean" ref="annotationSessionFactoryBean"/>
    </bean>

在我的 hibernateUserProfileDAO 中,我想像这样获取当前会话

    public class HibernateUserProfileDAO implements UserProfileDAO {
      private AnnotationSessionFactoryBean annotationSessionFactoryBean;

      public UserProfile getUserProfile() {
    Session session = annotationSessionFactoryBean.getCurrentSession();
      ....
      }

但我看到 AnnotationFactoryBean 中没有公共的 getCurrentSession() 方法。我发现只有受保护的 getAnnotationSession() 方法,但它也在抽象会话工厂类中。

谁能告诉我哪里出错了?

【问题讨论】:

    标签: hibernate spring spring-mvc


    【解决方案1】:

    AnnotationSessionFactoryBean是自动生产SessionFactory的工厂(Spring在内部处理),所以你需要按如下方式使用:

    <bean id="sf" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">        
        ...
    </bean>    
    
    <bean id="hibernateUserProfileDAO" class="com.springheatmvn.Dao.impl.hibernate.HibernateUserProfileDAO">
         <property name="sf" ref="sf"/>
    </bean>
    

    .

    public class HibernateUserProfileDAO implements UserProfileDAO {
        private SessionFactory sf;    
        ...
    }
    

    然后你通过调用sf.getCurrentSession()获得Session

    【讨论】:

    • 抱歉,这让我更加困惑了,如何将 spring 的 annotationSessionFactoryBean 的实例转换为 org.hiberate.SessionFactory 的实例?
    • 我问这一切的原因是因为当我试图做 sf.getCurrentSession() 我得到以下异常: org.hibernate.HibernateException: No Hibernate Session bound to thread ,并且配置不允许在这里创建非事务性的
    • SessionFactory created by AnnotationSessionFactoryBean 旨在用于 Spring 管理的事务,see docs
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    相关资源
    最近更新 更多