hibernatesessionfactory.java

来自「一个基本的图书馆管理系统」· Java 代码 · 共 116 行

JAVA
116
字号
package c18.dao;

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

/**
 * Hibernate 辅助类,用于生成与释放Hibernate会话
 * @author yuxd
 *
 */
public class HibernateSessionFactory {
	/**
	 * 日志操作对象
	 */
    private static final Log log = LogFactory.getLog(HibernateSessionFactory.class);
	/**
	 * 配置文件位置
	 */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
    /**
     * 本地会话
     */
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	/**
	 * 配置对象
	 */
    private  static Configuration configuration = new Configuration();
    /**
     * 会话工厂
     */
    private static org.hibernate.SessionFactory sessionFactory;
    /**
     * 配置文件
     */
    private static String configFile = CONFIG_FILE_LOCATION;

    private HibernateSessionFactory() {
    }

	/**
     * 返回本地会话实例
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
    	//得到本地会话
        Session session = (Session) threadLocal.get();
        
        //如果为空,重建会话工厂,取得会话
		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}

        return session;
    }

	/**
     *  重建会话工厂
     *
     */
	public static void rebuildSessionFactory() {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			log.error("%%%% Error Creating SessionFactory %%%%", e);
		}
	}

	/**
     *  关闭单一的会话对象
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

	/**
     *  返回会话工厂
     *
     */
	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
     *  设置配置文件,会话工厂将在后面被重建
     */
	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}

	/**
     *  返回Hibernate配置对象
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}
}

⌨️ 快捷键说明

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