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

📄 hibernatesessionfactory.java

📁 这是一个网上书店
💻 JAVA
字号:
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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -