title: Hibernate transaction manager configurations in Spring
body: <p>In my project I use Hibernate with programmatic transaction demarcation.
  Every time in my Service methods i write something similar to this.</p>
  <pre><code>Session session = HibernateUtil.getSessionFactory().openSession();
  session.beginTransaction();
  .. perform operation here
  session.getTransaction().commit();
  </code></pre>
  <p>Now I'm going to refactor my code with declarative transaction management. What I got now ...</p>
  <pre><code>  &lt;context:component-scan base-package=&quot;package.*&quot;/&gt;
    
    &lt;bean id=&quot;mySessionFactory&quot; class=&quot;org.springframework.orm.hibernate3.LocalSessionFactoryBean&quot;&gt;
      &lt;property name=&quot;configLocation&quot; value=&quot;classpath:hibernate.cfg.xml&quot;&gt;&lt;/property&gt;
      &lt;property name=&quot;configurationClass&quot;&gt;
          &lt;value&gt;org.hibernate.cfg.AnnotationConfiguration&lt;/value&gt;
      &lt;/property&gt;
    &lt;/bean&gt;
    
    &lt;tx:annotation-driven transaction-manager=&quot;txManager&quot;/&gt;
    
    
    &lt;bean id=&quot;txManager&quot;  class=&quot;org.springframework.orm.hibernate3.HibernateTransactionManager&quot;&gt;
      &lt;property name=&quot;sessionFactory&quot;&gt;
           &lt;ref local=&quot;mySessionFactory&quot;/&gt;
      &lt;/property&gt;
    &lt;/bean&gt;
  </code></pre>
  <p>Service class:</p>
  <pre><code>@Service
  public class TransactionalService {
  
      @Autowired
      private SessionFactory factory;
      
      @Transactional
      public User performSimpleOperation() {
          return (User)factory.getCurrentSession().load(User.class, 1L);
      }
  }
  </code></pre>
  <p>And simple test -</p>
  <pre><code>@Test
  public void useDeclarativeDem() {
      FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(&quot;spring-config.xml&quot;);
      TransactionalService b = (TransactionalService)ctx.getBean(&quot;transactionalService&quot;);
       User op = b.performSimpleOperation();
       op.getEmail();
  </code></pre>
  <p>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.</p>
  <ol>
  <li><p>what I am doing wrong here?</p>
  </li>
  <li><p>Is this approach valid?</p>
  </li>
  <li><p>Can you suggest any opensources project which works on spring/hibernate with annotation based configuration?</p>
  </li>
  </ol>
  <p><strong>Update</strong></p>
  <p>For some reason if I replace <em>getCurrentSession</em> with <em>openSession</em> this code works fine. Can someone explain it please?</p>