⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 hibernateutil.java

📁 一个专门用来快速开发网站的框架
💻 JAVA
字号:
package com.core.persistence;

/**
 * 这个类使用线程提供对Session、Transaction、SessionFactory的访问。
 * 为使用者提供简单统一的访问方式。
 */
import org.hibernate.HibernateException;
import org.hibernate.Interceptor;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 基本的Hibernate帮助类, 可以操作SessionFactory, Session and Transaction.
 * 使用静态初始化程序创建SessionFactory,把保存Session和Transactions保存在本地线程变量中。
 * 所有的异常都包装到新的异常类。
 */
public class HibernateUtil {

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

    private static Configuration configuration;
    private static SessionFactory sessionFactory;
    private static final ThreadLocal threadSession = new ThreadLocal();
    private static final ThreadLocal threadTransaction = new ThreadLocal();
    private static final ThreadLocal threadInterceptor = new ThreadLocal();

    /**
     * 在Web服务器启动时就会运行以下块。
     * 依据缺省配置文件创建初始的SessionFactory。
     */
    static {
        try {
            configuration = new Configuration();
            sessionFactory = configuration.configure("hibernate.cfg.xml").buildSessionFactory();
        } catch (Throwable ex) {
            // 这儿必须捕获Throwable,否则会遗漏NoClassDefFoundError和其他Error的父类。
            log.error("Building SessionFactory failed.------------------------------------------", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    /**
     * 返回SessionFactory用于这个静态类。
     */
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     * 返回Hibernate的原始configuration。
     */
    public static Configuration getConfiguration() {
        return configuration;
    }

    /**
     * 使用Configuration重新创建SessionFactory.
     */
    public static void rebuildSessionFactory() throws PersistenceException {
        synchronized (sessionFactory) {
            try {
                sessionFactory = getConfiguration().buildSessionFactory();
            } catch (Exception ex) {
                throw new PersistenceException(ex);
            }
        }
    }

    /**
     * 使用给定的Configuration重新创建SessionFactory.
     */
    public static void rebuildSessionFactory(Configuration cfg) throws PersistenceException {
        synchronized (sessionFactory) {
            try {
                sessionFactory = cfg.buildSessionFactory();
                configuration = cfg;
            } catch (Exception ex) {
                throw new PersistenceException(ex);
            }
        }
    }

    /**
     * 重新得到本地线程中的Session。
     * 如果当前Session没有打开,为当前运行的线程打开一个Session。
     */
    public static Session getSession() throws PersistenceException {
        Session s = (Session) threadSession.get();
        try {
            if (s == null) {
                log.debug("Opening new Session for this thread.");
                if (getInterceptor() != null) {
                    log.debug("Using interceptor: " + getInterceptor().getClass());
                    s = getSessionFactory().openSession(getInterceptor());
                } else {
                    s = getSessionFactory().openSession();
                }
                threadSession.set(s);
            }
        } catch (HibernateException ex) {
            throw new PersistenceException(ex);
        }
        return s;
    }

    /**
     * 把Session放回本地线程中。
     */
    public static void closeSession() throws PersistenceException {
        try {
            Session s = (Session) threadSession.get();
            threadSession.set(null);
            if (s != null && s.isOpen()) {
                log.debug("Closing Session of this thread.");
                s.close();
            }
        } catch (HibernateException ex) {
            throw new PersistenceException(ex);
        }
    }

    /**
     * 开始一个数据库事务。
     */
    public static void beginTransaction() throws PersistenceException {
        Transaction tx = (Transaction) threadTransaction.get();
        try {
            if (tx == null) {
                log.debug("Starting new database transaction in this thread.");
                tx = getSession().beginTransaction();
                threadTransaction.set(tx);
            }
        } catch (HibernateException ex) {
            throw new PersistenceException(ex);
        }
    }

    /**
     * 提交数据库事务。
     */
    public static void commitTransaction() throws PersistenceException {
        Transaction tx = (Transaction) threadTransaction.get();
        try {
            if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
                log.debug("Committing database transaction of this thread.");
                tx.commit();
            }
            threadTransaction.set(null);
        } catch (HibernateException ex) {
            rollbackTransaction();
            throw new PersistenceException(ex);
        }
    }

    /**
     * 回滚数据库事务。
     */
    public static void rollbackTransaction() throws PersistenceException {
        Transaction tx = (Transaction) threadTransaction.get();
        try {
            threadTransaction.set(null);
            if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
                log.debug("Tyring to rollback database transaction of this thread.");
                tx.rollback();
            }
        } catch (HibernateException ex) {
            throw new PersistenceException(ex);
        } finally {
            closeSession();
        }
    }

    /**
     * 用参数中的Hibernate Session重新和当前线程连接。
     */
    public static void reconnect(Session session) throws PersistenceException {
        try {
            session.reconnect();
            threadSession.set(session);
        } catch (HibernateException ex) {
            throw new PersistenceException(ex);
        }
    }

    /**
     * 放回当前线程中的Session,然后和线程断开。
     */
    public static Session disconnectSession() throws PersistenceException {
        Session session = getSession();
        try {
            threadSession.set(null);
            if (session.isConnected() && session.isOpen())
                session.disconnect();
        } catch (HibernateException ex) {
            throw new PersistenceException(ex);
        }
        return session;
    }

    /**
     * 用当前线程注册Hibernate拦截器。
     * 注册以后,每一个Session打开都会被拦截。如果已经打开就不会拦截。
     */
    public static void registerInterceptor(Interceptor interceptor) {
        threadInterceptor.set(interceptor);
    }

    /**
     * 得到当前线程的Hibernate拦截器。
     */
    private static Interceptor getInterceptor() {
        Interceptor interceptor = (Interceptor) threadInterceptor.get();
        return interceptor;
    }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -