---
title: "HibernateUtil范例"
author: "lkf009"
date: "2012-08-10T17:39:42Z"
tags: []
categories: ["编程语言"]
slug: "hibernateutil"
draft: false
lastmod: "2012-08-10T17:39:42Z"
id: 1628516
url: "https://lkf009.iteye.com/blog/1628516"
---

HibernateUtil往往是用来生成SessionFactory以及getSession与closeSession的，主要是几个静态方法。

一、使用ThreadLocal隔离执行所使用的数据，避开Session多线程之间数据共享问题，主要是几个静态方法：

import org.apache.commons.logging.Log;  
import org.apache.commons.logging.LogFactory;  
import org.hibernate.Session;  
import org.hibernate.SessionFactory;  
import org.hibernate.cfg.Configuration;

public class HibernateUtil {  
private static final Log log=LogFactory.getLog(HibernateUtil.class);

private static final SessionFactory sessionFactory;  
static  
{  
        try{  
              sessionFactory=new Configuration().configure().buildSessionFactory();  
     
       }catch(Throwable ex)  
       {  
              log.error("Initial SessionFactory creation failed.",ex);  
              throw new ExceptionInInitializerError(ex);  
       }  
}  
public static final ThreadLocal thread\_var=new ThreadLocal();

public static Session currentSession()  
{  
      Session s=(Session)thread\_var.get();  
       if(s==null)  
      {  
        s=sessionFactory.openSession();  
          thread\_var.set(s);  
    }  
     return s;  
}

public static void closeSession()  
{  
       Session s=(Session)thread\_var.get();  
      if(s!=null)  
              s.close();  
       thread\_var.set(null);  
}  
}

二、不使用ThreadLocal的：

import org.hibernate.HibernateException;  
import org.hibernate.Session;  
import org.hibernate.SessionFactory;  
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

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

    public static Session currentSession() throws HibernateException {  
        Session s = sessionFactory.openSession();  
        return s;  
    }

    public static void closeSession(Session s) {  
        s.close();  
    }  
}

三、用MyEclipse自动生成的HibernateUtil：

import org.hibernate.HibernateException;  
import org.hibernate.Session;  
import org.hibernate.cfg.Configuration;

/\**  
\* Configures and provides access to Hibernate sessions, tied to the  
\* current thread of execution. Follows the Thread Local Session  
\* pattern, see [{@link](mailto:%7B@link) [http://hibernate.org/42.html](http://hibernate.org/42.html) }.  
\*/  
public class HibernateSessionFactory {

    /\**   
     * Location of hibernate.cfg.xml file.  
     * Location should be on the classpath as Hibernate uses   
     * #resourceAsStream style lookup for its configuration file.   
     * The default classpath location of the hibernate config file is   
     * in the default package. Use #setConfigFile() to update   
     * the location of the configuration file for the current session.     
     \*/  
    private static String CONFIG\_FILE\_LOCATION = "/hibernate.cfg.xml";  
    private static final ThreadLocal&lt;Session&gt; threadLocal = new ThreadLocal&lt;Session&gt;();  
    private static Configuration configuration = new Configuration();      
    private static org.hibernate.SessionFactory sessionFactory;  
    private static String configFile = CONFIG\_FILE\_LOCATION;

static {  
    try {  
       configuration.configure(configFile);  
        sessionFactory = configuration.buildSessionFactory();  
       } catch (Exception e) {  
      System.err.println("%%%% Error Creating SessionFactory %%%%");  
      e.printStackTrace();  
    }  
    }  
    private HibernateSessionFactory() {  
    }

/\**  
     * Returns the ThreadLocal Session instance. Lazy initialize  
     * the &lt;code&gt;SessionFactory&lt;/code&gt; if needed.  
     *  
     * @return Session  
     * @throws HibernateException  
     \*/  
    public static Session getSession() 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;  
    }

/\**  
     * Rebuild hibernate session factory  
     *  
     \*/  
public static void rebuildSessionFactory() {  
   try {  
    configuration.configure(configFile);  
    sessionFactory = configuration.buildSessionFactory();  
   } catch (Exception e) {  
    System.err  
      .println("%%%% Error Creating SessionFactory %%%%");  
    e.printStackTrace();  
   }  
}

/\**  
     * Close the single hibernate session instance.  
     *  
     * @throws HibernateException  
     \*/  
    public static void closeSession() throws HibernateException {  
        Session session = (Session) threadLocal.get();  
        threadLocal.set(null);

        if (session != null) {  
            session.close();  
        }  
    }

/\**  
     * return session factory  
     *  
     \*/  
public static org.hibernate.SessionFactory getSessionFactory() {  
   return sessionFactory;  
}

/\**  
     * return session factory  
     *  
     * session factory will be rebuilded in the next call  
     \*/  
public static void setConfigFile(String configFile) {  
   HibernateSessionFactory.configFile = configFile;  
   sessionFactory = null;  
}

/\**  
     * return hibernate configuration  
     *  
     \*/  
public static Configuration getConfiguration() {  
   return configuration;  
}

}