How to access hibernate session via AnnotationSessionFactoryBean?

不羁的心 提交于 2020-01-14 02:51:09

问题


I want to integrate hibernate with spring. spring 3 documentation says that you can access session via org.hiberate.SessionFactory's getCurrentSession() and this should be prefered over hibernateDaoSupport approach.

But I want to know how can we get hold of org.hiberate.SessionFactory's instance in the first place if we are using AnnotationSessionFactoryBean? I have done the following bean declaration in applicationContext.xml:

       <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 which is using the session:

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

In my hibernateUserProfileDAO I would like to get the current session like this

    public class HibernateUserProfileDAO implements UserProfileDAO {
      private AnnotationSessionFactoryBean annotationSessionFactoryBean;

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

But I see that there is no public getCurrentSession() method in AnnotationFactoryBean. I found only protected getAnnotationSession() method but it is also on Abstract session factory class.

Can any one please tell me where am i going wrong?


回答1:


AnnotationSessionFactoryBean is a factory that produces SessionFactory automatically (Spring handles in internally), so that you need to use it as follows:

<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;    
    ...
}

Then you obtain a Session by calling sf.getCurrentSession().



来源:https://stackoverflow.com/questions/7389239/how-to-access-hibernate-session-via-annotationsessionfactorybean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!