0

Hi I'm trying to obtain hibernate's Session through Spring's injection.

Here's my spring context xml:

  <!-- hibernate's session factory -->
  <bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="configLocation">
      <value>classpath:./hibernate.cfg.xml</value>
    </property>
  </bean>

  <!-- the transaction manager -->
  <bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
  </bean>

Here's the code:

private static ApplicationContext ctx;

    if (ctx == null) {
        ctx = new ClassPathXmlApplicationContext("springContext.xml");
    }
    LocalSessionFactoryBean sf = ctx.getBean(LocalSessionFactoryBean.class);
    session = sf.getObject().getCurrentSession();

However the session I obtain is null.

Is it correct to get Session through sf.getObject().getCurrentSession() ?

Thanks :)

Will Sumekar
  • 1,249
  • 5
  • 16
  • 25

1 Answers1

1

I don't think you should access the session like that. Either use HibernateTemplate or inject SessionFactory in your beans and call getCurrentSession() on it. Otherwise your transaction management won't be handled properly

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140