hibernatesessionfactory.java

来自「这是一个网上书店」· Java 代码 · 共 99 行

JAVA
99
字号
package com.ebookstore.common;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateSessionFactory {

	// 配置文件
	private static String CONFIG_FILE_LOCATION = "com/ebookstore/config/hibernate.cfg.xml";

	// 本地线程
	private static final ThreadLocal threadLocal = new ThreadLocal();

	// 配置对象
	private static Configuration configuration = new Configuration();

	// 会话工厂
	private static SessionFactory sessionFactory;

	// 配置文件
	private static String configFile = CONFIG_FILE_LOCATION;

	private HibernateSessionFactory() {
	}

	/**
	 * 获得当前的会话
	 * 
	 * @return Session
	 * @throws HibernateException
	 */
	public static Session getCurrentSession() 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) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	/**
	 * 关闭当前会话
	 * 
	 * @throws HibernateException
	 */
	public static void closeCurrentSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
		threadLocal.set(null);

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

	/**
	 * 获得会话工厂对象
	 */
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * 设置配置文件
	 */
	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}

	/**
	 * 获得配置文件
	 */
	public static Configuration getConfiguration() {
		return configuration;
	}

}

⌨️ 快捷键说明

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