`

HibernateUtil

阅读更多
package org.hibernate.auction.persistence;

import net.sf.hibernate.*;
import net.sf.hibernate.cfg.Configuration;
import org.apache.commons.logging.*;
import org.hibernate.auction.exceptions.InfrastructureException;

import javax.naming.*;

/**
 * Basic Hibernate helper class, handles SessionFactory, Session and Transaction.
 * <p>
 * Uses a static initializer for the initial SessionFactory creation
 * and holds Session and Transactions in thread local variables. All
 * exceptions are wrapped in an unchecked InfrastructureException.
 *
 * @author christian@hibernate.org
 */
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();

	// Create the initial SessionFactory from the default configuration files
	static {
		try {
			configuration = new Configuration();
			sessionFactory = configuration.configure().buildSessionFactory();
			// We could also let Hibernate bind it to JNDI:
			// configuration.configure().buildSessionFactory()
		} catch (Throwable ex) {
			// We have to catch Throwable, otherwise we will miss
			// NoClassDefFoundError and other subclasses of Error
			log.error("Building SessionFactory failed.", ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	/**
	 * Returns the SessionFactory used for this static class.
	 *
	 * @return SessionFactory
	 */
	public static SessionFactory getSessionFactory() {
		/* Instead of a static variable, use JNDI:
		SessionFactory sessions = null;
		try {
			Context ctx = new InitialContext();
			String jndiName = "java:hibernate/HibernateFactory";
			sessions = (SessionFactory)ctx.lookup(jndiName);
		} catch (NamingException ex) {
			throw new InfrastructureException(ex);
		}
		return sessions;
		*/
		return sessionFactory;
	}

	/**
	 * Returns the original Hibernate configuration.
	 *
	 * @return Configuration
	 */
	public static Configuration getConfiguration() {
		return configuration;
	}

	/**
	 * Rebuild the SessionFactory with the static Configuration.
	 *
	 */
	 public static void rebuildSessionFactory()
		throws InfrastructureException {
		synchronized(sessionFactory) {
			try {
				sessionFactory = getConfiguration().buildSessionFactory();
			} catch (Exception ex) {
				throw new InfrastructureException(ex);
			}
		}
	 }

	/**
	 * Rebuild the SessionFactory with the given Hibernate Configuration.
	 *
	 * @param cfg
	 */
	 public static void rebuildSessionFactory(Configuration cfg)
		throws InfrastructureException {
		synchronized(sessionFactory) {
			try {
				sessionFactory = cfg.buildSessionFactory();
				configuration = cfg;
			} catch (Exception ex) {
				throw new InfrastructureException(ex);
			}
		}
	 }

	/**
	 * Retrieves the current Session local to the thread.
	 * <p/>
	 * If no Session is open, opens a new Session for the running thread.
	 *
	 * @return Session
	 */
	public static Session getSession()
		throws InfrastructureException {
		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 InfrastructureException(ex);
		}
		return s;
	}

	/**
	 * Closes the Session local to the thread.
	 */
	public static void closeSession()
		throws InfrastructureException {
		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 InfrastructureException(ex);
		}
	}

	/**
	 * Start a new database transaction.
	 */
	public static void beginTransaction()
		throws InfrastructureException {
		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 InfrastructureException(ex);
		}
	}

	/**
	 * Commit the database transaction.
	 */
	public static void commitTransaction()
		throws InfrastructureException {
		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 InfrastructureException(ex);
		}
	}

	/**
	 * Commit the database transaction.
	 */
	public static void rollbackTransaction()
		throws InfrastructureException {
		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 InfrastructureException(ex);
		} finally {
			closeSession();
		}
	}

	/**
	 * Reconnects a Hibernate Session to the current Thread.
	 *
	 * @param session The Hibernate Session to be reconnected.
	 */
	public static void reconnect(Session session)
		throws InfrastructureException {
		try {
			session.reconnect();
			threadSession.set(session);
		} catch (HibernateException ex) {
			throw new InfrastructureException(ex);
		}
	}

	/**
	 * Disconnect and return Session from current Thread.
	 *
	 * @return Session the disconnected Session
	 */
	public static Session disconnectSession()
		throws InfrastructureException {

		Session session = getSession();
		try {
			threadSession.set(null);
			if (session.isConnected() && session.isOpen())
				session.disconnect();
		} catch (HibernateException ex) {
			throw new InfrastructureException(ex);
		}
		return session;
	}

	/**
	 * Register a Hibernate interceptor with the current thread.
	 * <p>
	 * Every Session opened is opened with this interceptor after
	 * registration. Has no effect if the current Session of the
	 * thread is already open, effective on next close()/getSession().
	 */
	public static void registerInterceptor(Interceptor interceptor) {
		threadInterceptor.set(interceptor);
	}

	private static Interceptor getInterceptor() {
		Interceptor interceptor =
			(Interceptor) threadInterceptor.get();
		return interceptor;
	}

}
分享到:
评论

相关推荐

    HibernateUtil分装完整版HQL查询

    标题"HibernateUtil分装完整版HQL查询"暗示了这是一个关于使用HibernateUtil工具类来封装和执行HQL(Hibernate Query Language)查询的教程或代码示例。描述中的重复信息进一步强调了这个主题,意味着我们将探讨如何...

    HibernateUtil 分页 增删改查 封装

    HibernateUtil 分页 增删改查 封装 HibernateUtil 分页 增删改查 封装 HibernateUtil 分页 增删改查 封装

    hibernate入门实例封装了HibernateUtil

    【标题】:Hibernate入门实例——基于HibernateUtil的数据库操作封装 在Java开发中,Hibernate作为一个强大的对象关系映射(ORM)框架,极大地简化了数据库操作。本实例将深入浅出地介绍如何使用Hibernate进行基本...

    06_传智播客hibernate教程_完善HibernateUtil类及hql查询入门

    本教程聚焦于“完善HibernateUtil类及HQL查询入门”,让我们深入探讨这两个关键概念。 首先,`HibernateUtil` 类是 Hibernate 教程中常见的一种工具类,它的主要作用是提供对 Hibernate 框架的简单封装,以方便进行...

    HibernateUtil工具类

    HibernateUtil工具类

    hibernate 一对多测试工程

    Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); Class class1 = new Class(); // set class1 properties List&lt;Student&gt; students =...

    HibernateUtil.java Hibernate5.2.1

    Hibernate5.2.1 的工具类 创建session 和 sessionFactory

    java util工具类

    HibernateUtil.java HibernateUtils.java HttpRequester.java HttpRespons.java HttpUtil.java MD5Util.java Pagination.java PropertiesUtil.java RegUtil.java StringUtil.java UploadUtil.java UUIDUtils.java

    Hibernate工具类

    `HibernateUtil`工具类就是对Hibernate框架功能的一种封装,简化了对数据库的操作。 在`HibernateUtil`工具类中,常见的方法有以下几类: 1. **初始化SessionFactory**: SessionFactory是Hibernate的核心组件,它...

    hibernateUtil.txt

    欢迎大家咨询,我会尽量去与大家讲解,希望对你们有所帮助

    对DAO编写单元测试源代码

    } &lt;br&gt; public String createPasswordTicket(User user) { HibernateUtil.executeUpdate( "delete from PasswordTicket as pt where pt.user=?", new Object[] { user } ); String ...

    基于泛型的通用Dao接口和hibernate的实现

    return HibernateUtil.getSession().createCriteria(clazz).list(); } @SuppressWarnings("unchecked") public List&lt;T&gt; findList(int pageNo, int pageSize) { return HibernateUtil.getSession()....

    hibernate学习笔记

    - **编写 HibernateUtil 工具类**:用于获取SessionFactory和Session,简化操作。 - **编写数据访问层**:使用HibernateUtil,实现CRUD(创建、读取、更新、删除)操作。 2. **Domain Object 规范** - **无参...

    hibernate 的各种操作

    Session session = HibernateUtil.currentSession(); // 获取当前会话 Transaction tx = null; // 事务 Users po = new Users(); // 实体对象 po = transCommerceInfoVOtoPO(vo, po); // 将 VO 转换为 PO try...

    案例课程B-S架构-1期 详细设计书9-公告管理模块.pdf

    - 模型层:在HibernateUtil中增加了公告新增的业务逻辑方法,接收封装用户输入的实体对象。 4. **公告删除** - 界面层:删除操作在公告列表页面中进行,无单独的删除界面。若用户无权限,会显示bbc_nomodify.jsp...

    六种方式实现hibernate查询

    s=HibernateUtil.getSession(); String hql="from Admin as admin where admin.aname=:name"; Query query=s.createQuery(hql); query.setString("name", name); List&lt;Admin&gt; list=query.list(); for(Admin ...

    案例课程B-S架构-1期 详细设计书18-审核批示模块.pdf

    控制层的`updateShen.jsp`逻辑页面接收用户输入,调用`HibernateUtil`中的`updateshenhe()`方法进行更新操作,并根据执行结果决定页面跳转。 3. **申请的审核**:未提供详细设计,通常涉及用户提交审批申请的功能。...

Global site tag (gtag.js) - Google Analytics