java - Hibernate 打开/关闭 session ,DAO 的正确方法

标签 java hibernate session dao sessionfactory

我已经编写了这个 Hibernate 对象 DAO,但是使用这种方法时,它使用每次更新方法的 session (我认为这是不正确的)。

我认为它不对的原因是我的 User 类遇到了问题,该类包含延迟获取的集合。因为从 DAO 中检索每个用户时, session 已关闭。因此我无法获得我的 Collection 。

有时,它还会对表进行大量不必要的更新,因为对象已分离。

那么有什么方法可以修复我的 DAO,比如使用 getCurrentSession()

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import org.test.util.DataAccessLayerException;
import org.test.util.HibernateUtil;

public abstract class AbstractDao {
    protected Session session;
    protected Transaction tx;
    public AbstractDao() {
        HibernateUtil.buildIfNeeded();
    }
    protected void saveOrUpdate(Object obj) {
        try {
            startOperation();
            session.saveOrUpdate(obj);
            tx.commit();
        } catch (HibernateException e) {
            handleException(e);
        } finally {
            HibernateUtil.close(session);
        }
    }
    protected void delete(Object obj) {
        try {
            startOperation();
            session.delete(obj);
            tx.commit();
        } catch (HibernateException e) {
            handleException(e);
        } finally {
            HibernateUtil.close(session);
        }
    }
    protected Object find(Class clazz, Long id) {
        Object obj = null;
        try {
            startOperation();
            obj = session.load(clazz, id);
            tx.commit();
        } catch (HibernateException e) {
            handleException(e);
        } finally {
            HibernateUtil.close(session);
        }
        return obj;
    }
    protected List findAll(Class clazz) {
        List objects = null;
        try {
            startOperation();
            Query query = session.createQuery("from " + clazz.getName());
            objects = query.list();
            tx.commit();
        } catch (HibernateException e) {
            handleException(e);
        } finally {
            HibernateUtil.close(session);
        }
        return objects;
    }
    protected void handleException(HibernateException e) throws DataAccessLayerException {
        HibernateUtil.rollback(tx);
        throw new DataAccessLayerException(e);
    }
    protected void startOperation() throws HibernateException {
        session = HibernateUtil.openSession();
        tx = session.beginTransaction();
    }
}

hibernate 工具

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static Log log = LogFactory.getLog(HibernateUtil.class);
    private static SessionFactory sessionFactory;

    private static SessionFactory configureSessionFactory()
            throws HibernateException {
        Configuration configuration = new Configuration();
        configuration.configure();
        sessionFactory = configuration.buildSessionFactory();
        return sessionFactory;
    }

    public static SessionFactory buildIfNeeded()
            throws DataAccessLayerException {
        if (sessionFactory != null) {
            return sessionFactory;
        }
        try {
            return configureSessionFactory();
        } catch (HibernateException e) {
            throw new DataAccessLayerException(e);
        }
    }

    public static SessionFactory buildSessionFactory()
            throws HibernateException {
        if (sessionFactory != null) {
            closeFactory();
        }
        return configureSessionFactory();
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static Session openSession() throws HibernateException {
        buildIfNeeded();
        return sessionFactory.openSession();
    }

    public static void closeFactory() {
        if (sessionFactory != null) {
            try {
                sessionFactory.close();
            } catch (HibernateException ignored) {
                log.error("Couldn't close SessionFactory", ignored);
            }
        }
    }

    public static void close(Session session) {
        if (session != null) {
            try {
                session.close();
            } catch (HibernateException ignored) {
                log.error("Couldn't close Session", ignored);
            }
        }
    }

    public static void rollback(Transaction tx) {
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (HibernateException ignored) {
            log.error("Couldn't rollback Transaction", ignored);
        }
    }
}

最佳答案

好的方法是将 close 方法添加到您的 DAO(AbstractDao) 并将其称为“工作单元”的结尾。

而且,请不要对 session 进行静态引用, session 不是线程安全的


这里有一个很好的示例解释:Link

关于java - Hibernate 打开/关闭 session ,DAO 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8841207/

相关文章:

java - 如何检查 JTextField 是否为空?

java - Cloud Firestore 保存带有不必要小数位的数字

java - 查找最近点(不包括最后点)LibGDX Java

java - 与 Hibernate 的只读数据库连接

java - 带有 @MappedSuperclass 和 @ManyToOne 的列名称

php - session_start() : Session data file is not created by your uid

java - 首次运行 jhipster 应用程序失败,启动 tomcat 上下文时出错

hibernate - 如何排除 JBoss 提供的 javax.persistence 模块?

asp.net - 比 session 更持久?

php - 为什么要测试 session 是否已启动