title: Hibernate SessionFactory vs Spring LocalSessionFactoryBean
body: <p>I am trying to move a spring3.2.x + hibernate4.x setup from a xml to java configuration.<br>
  Heres a snippet of the existing code:</p>
  
  <pre><code>import org.hibernate.SessionFactory;
  import org.hibernate.Query;
  import org.hibernate.Session;
  
  public class StockDaoImpl implements StockDao{
  
      private SessionFactory sessionFactory;
      public SessionFactory getSessionFactory() {
          return sessionFactory;}
      public void setSessionFactory(SessionFactory sessionFactory) {
           this.sessionFactory = sessionFactory;
      }
  
      public void save(Stock stock){
          Session session = getSessionFactory().openSession();
          try{
          session.save(stock);
          }
          finally{
          session.close();
          }
      }
  </code></pre>
  
  <p>The spring config file</p>
  
  <pre><code>&lt;!-- Stock Data Access Object --&gt;
     &lt;bean id="stockDao" class="com.data.dao.StockDaoImpl" &gt;
          &lt;property name="sessionFactory" ref="sessionFactory"&gt;&lt;/property&gt;
     &lt;/bean&gt; 
  
      &lt;bean id="dataSource"&gt;
  .....
  &lt;/bean&gt;
  
      &lt;bean id="sessionFactory" 
           class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt;
  
          &lt;property name="dataSource"&gt;
            &lt;ref bean="dataSource"/&gt;
          &lt;/property&gt;
          &lt;property name="hibernateProperties"&gt;
             ......
           &lt;/property&gt;
          &lt;property name="mappingResources"&gt;
          .......
          &lt;/property&gt; 
      &lt;/bean&gt;
  </code></pre>
  
  <p>This works fine - but how do i re-define this config in java?<br>
  Heres an attempt -   </p>
  
  <pre><code>@Bean
      public StockDao stockDao() {
          StockDaoImpl dao=new StockDaoImpl();
          dao.setSessionFactory(sessionFactory());
          return dao;
      }
  
  ......
     @Bean
     public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(restDataSource());
        sessionFactory.setPackagesToScan(new String[] { .....});
        sessionFactory.setHibernateProperties(hibernateProperties());
  
        return sessionFactory;
     }
  </code></pre>
  
  <p>But this wont compile as the <code>sessionFactory</code> being referred to is not Spring's LocalSessionFactoryBean? </p>
  
  <p>How do I reconcile this? </p>