【问题标题】:Hibernate/Spring newbie architectureHibernate/Spring 新手架构
【发布时间】:2012-06-25 18:58:59
【问题描述】:

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



}

【问题讨论】:

  • 你所拥有的对我来说似乎很简单......

标签: spring hibernate


【解决方案1】:
  1. @Autowired 不适用于 static 字段。

  2. 从 DAO 控制事务没有多大意义,因为事务边界通常在服务层中定义,因此单个事务可能涉及多个 DAO。

  3. 为什么需要所有这些东西? Spring 可以隐含地为您完成,请参阅 10. Transaction Management13.3 Hibernate。您只需定义事务边界(使用@TransacionalTransactionTemplate)并在您的DAO 中以sessionFactory.getCurrentSession() 获取当前会话。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 2011-03-26
    • 2018-12-02
    • 2018-04-03
    • 1970-01-01
    • 2015-05-06
    • 2010-12-24
    相关资源
    最近更新 更多