Hibernate transaction manager configurations in Spring

user12384512 picture user12384512 · Feb 27, 2011 · Viewed 55.1k times · Source

In my project I use Hibernate with programmatic transaction demarcation. Every time in my Service methods i write something similar to this.

Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
.. perform operation here
session.getTransaction().commit();

Now I'm going to refactor my code with declarative transaction management. What I got now ...

  <context:component-scan base-package="package.*"/>
  
  <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
    <property name="configurationClass">
        <value>org.hibernate.cfg.AnnotationConfiguration</value>
    </property>
  </bean>
  
  <tx:annotation-driven transaction-manager="txManager"/>
  
  
  <bean id="txManager"  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory">
         <ref local="mySessionFactory"/>
    </property>
  </bean>

Service class:

@Service
public class TransactionalService {

    @Autowired
    private SessionFactory factory;
    
    @Transactional
    public User performSimpleOperation() {
        return (User)factory.getCurrentSession().load(User.class, 1L);
    }
}

And simple test -

@Test
public void useDeclarativeDem() {
    FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext("spring-config.xml");
    TransactionalService b = (TransactionalService)ctx.getBean("transactionalService");
     User op = b.performSimpleOperation();
     op.getEmail();

When I try to get user email outside of Transactional method, I got lazy initialization exception, email is my case is a simple string. Hibernate does not even perform sql query, until I call any getters on my POJO.

  1. what I am doing wrong here?

  2. Is this approach valid?

  3. Can you suggest any opensources project which works on spring/hibernate with annotation based configuration?

Update

For some reason if I replace getCurrentSession with openSession this code works fine. Can someone explain it please?

Answer

user12384512 picture user12384512 · Feb 28, 2011

Ok, finally i realized what was the problem. In code above i used load instead of get. Session.load did not actually hit the databased. That's the reason why i get lazy-initialization exception outside of @Transactional method

If i use openSession instead of getCurrentSession, session is opened outside of scope spring container. As result session was not close and it allow me to read object properties outside of @Transactional method