Will Sumekar
Will Sumekar

Reputation: 1269

Spring Config for Hibernate Session

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 :)

Upvotes: 0

Views: 1127

Answers (1)

Bozho
Bozho

Reputation: 597036

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

Upvotes: 1

Related Questions