title: Hibernate/Spring newbie architecture
body: <p>I have a project in Spring 3.1 and Hibernate 3.  I am trying to define my DAOs.  I have an abstract DAO class with methods for getting the session, committing, rollback, etc.  My problem is getting the SessionFactory injected into this class.  I am wondering if there is a better way of defining this class.  Thanks Eric</p>
  
  <pre><code>import org.hibernate.HibernateException;
  import org.hibernate.Session;
  import org.hibernate.SessionFactory;
  import org.springframework.beans.factory.annotation.Autowired;
  
  public abstract class AbstractDAO {
  
  
      @Autowired
      private static SessionFactory sessionFactory;
  
      private static final ThreadLocal&lt;Session&gt; threadLocal = new ThreadLocal&lt;Session&gt;();
  
      protected static Session getSession() {
          Session session = threadLocal.get();
          if (session == null) {
              session = sessionFactory.openSession();
              threadLocal.set(session);
          }
          return session;
      }
  
      protected void begin() {
          getSession().beginTransaction();
      }
  
      protected void commit() {
          getSession().getTransaction().commit();
      }
  
      protected void rollback() {
          try {
              getSession().getTransaction().rollback();
          }
          catch (HibernateException ex) {
              ex.printStackTrace();
          }           
          close();
      }
  
  
      protected void close() {
          try {
              getSession().close();
          }
          catch (HibernateException ex) {
              ex.printStackTrace();
          }
          threadLocal.set(null);
      }
  
  
  
  }
  </code></pre>