HibernateUtil.java
资源名称:shihua.rar [点击查看]
上传用户:zghglow
上传日期:2022-08-09
资源大小:27227k
文件大小:1k
源码类别:
WEB源码(ASP,PHP,...)
开发平台:
JavaScript
- package com.chinacannel.common;
- import net.sf.hibernate.*;
- import net.sf.hibernate.cfg.*;
- import org.apache.log4j.Logger;
- public class HibernateUtil {
- private static Logger log = Logger.getLogger(HibernateUtil.class);
- private static final SessionFactory sessionFactory;
- static {
- try {
- Configuration cfg=new Configuration().configure();
- sessionFactory = cfg.buildSessionFactory();
- } catch (HibernateException ex) {
- // throw new RuntimeException("Exception building SessionFactory: " + ex.getMessage(), ex);
- log.error(ex.getMessage());
- throw new RuntimeException("Exception building SessionFactory: " + ex.getMessage());
- /**@todo fatal log*/
- }
- }
- public static final ThreadLocal session = new ThreadLocal();
- public static Session currentSession() throws HibernateException {
- Session s = (Session) session.get();
- // Open a new Session, if this Thread has none yet
- if (s == null) {
- s = sessionFactory.openSession();
- session.set(s);
- }
- return s;
- }
- public static void closeSession() throws HibernateException {
- try {
- Session s = (Session) session.get();
- session.set(null);
- if (s != null) {
- s.close();
- }
- }
- catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- }