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

📄 hibernateutil.java

📁 办公自动化项目
💻 JAVA
字号:
package hong.javanet.dao;

import org.hibernate.*;
import org.hibernate.cfg.*;
import org.apache.log4j.Logger;
import hong.javanet.frame.*;

public class HibernateUtil {

  private static Logger log = Logger.getLogger(HibernateUtil.class);
  private static final SessionFactory sessionFactory;

  static {
    try {
      sessionFactory = new Configuration().configure().buildSessionFactory();
    }
    catch (Throwable ex) {
      log.fatal("Exception building SessionFactory: " + ex.getMessage(), ex);
      throw new RuntimeException("Exception building SessionFactory: " +
                                 ex.getMessage(), ex);
    }
  }

  private static final ThreadLocal session = new ThreadLocal();

//  public static Session currentSessionNoTransaction() 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 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();
//      Context ctx  = ContextUtil.getContext();
//      ctx.hibernateSession = s;
//      ctx.transaction = s.beginTransaction();
      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) {
      log.warn("error when close session " + ex.getMessage(), ex);
    }
  }
}

⌨️ 快捷键说明

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