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

📄 hibernateutil.java

📁 hibernate项目实践
💻 JAVA
字号:
package com.px1987.webbbs.dao;

import org.hibernate.*;
import org.hibernate.cfg.*;
public class HibernateUtil 
{
	private static final SessionFactory sessionFactory;
	/* 静态初始器,当JVM(Java虚拟机)加载HibernateUtil类时,会执行该静态代码块。
	 */
	static   
	{
		try
		{    // Create the SessionFactory
			sessionFactory = new Configuration().configure().buildSessionFactory();
			/*也可以采用下面的方式            
            Configuration hibernateConfiguration=new Configuration();
            sessionFactory = hibernateConfiguration.configure().buildSessionFactory();
			 */            
		}
		catch (Throwable ex) 
		{
			throw new ExceptionInInitializerError(ex);
		}
	}
	public static final ThreadLocal threadLocal = new ThreadLocal();
	public static final ThreadLocal tLocaltx = new ThreadLocal();    
	public static Session currentSession()  
	{
		Session currentSession = (Session) threadLocal.get();
		if (currentSession == null) 
		{
			currentSession = sessionFactory.openSession();
			threadLocal.set(currentSession);
		}
		return currentSession;
	}
	public static void closeSession() 
	{
		Session currentSession = (Session) threadLocal.get();
		if (currentSession != null)
			currentSession.close();
		threadLocal.set(null);
	}    
	public static void beginTransaction()
	{
		Transaction tx = (Transaction) tLocaltx.get();
		try
		{
			if (tx == null)
			{
				tx = currentSession().beginTransaction();
				tLocaltx.set(tx);
			}
		}
		catch (HibernateException e)
		{
			throw e;
		}
	}   
	public static void commitTransaction() 
	{
		Transaction tx = (Transaction) tLocaltx.get();
		try
		{
			if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack())
				tx.commit();
			tLocaltx.set(null);
		}
		catch (HibernateException e)
		{
			throw e;
		}
	}
	public static void rollbackTransaction()
	{
		Transaction tx = (Transaction) tLocaltx.get();
		try
		{
			tLocaltx.set(null);
			if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()){
				tx.rollback();
			}
		}
		catch (HibernateException e)
		{
			throw e;
		}
	}
}

⌨️ 快捷键说明

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