2012-06-25 262 views
1

我在Spring 3.1和Hibernate 3中有一個項目。我試圖定義我的DAO。我有一個抽象的DAO類,其中包含獲取會話,提交,回滾等方法。我的問題是將SessionFactory注入到此類中。我想知道是否有更好的方式來定義這個類。感謝埃裏克休眠/春季新手架構

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<Session> threadLocal = new ThreadLocal<Session>(); 

    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); 
    } 



} 
+0

你對我的看法很簡單... – hvgotcodes

回答

4
  1. @Autowired不上static下地幹活。

  2. 控制來自DAO的事務沒有多大意義,因爲事務邊界通常在服務層中定義,因此單個事務可能涉及多個DAO。

  3. 爲什麼你需要所有這些東西?春天可以暗中爲你做,見10. Transaction Management13.3 Hibernate。您只需要定義事務邊界(使用@TransacionalTransactionTemplate),並在您的DAO中獲取當前會話sessionFactory.getCurrentSession()

+0

+1。不要重新發明輪子。 – pap