2012-06-25 186 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