博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Hibernate 的工具类
阅读量:4220 次
发布时间:2019-05-26

本文共 5010 字,大约阅读时间需要 16 分钟。

Hibernate 的工具类

  对于Hibernate 3.1 以前的的版本在实现Hibernate工具类时,需要通过两个线程
局部变量来保存与当前进行相对应的Session和事务对象的实例.
  而对于Hibernate 3.1 以后的版本,使用线程局部变量保存Session和事务对象的
工作就完全不需要自己去实现了,只需在Hibernate.cfg.xml配置文件中增加一个名为
Current_session_context_class的属性,并且设置该属性的值为thread.这样Hibernate
就可以自动地使用线程局部变量来保存当前的进程的Session和事务对象了.
  相应地,Hibernate也为其Session对象增加了getTransaction()方法,以便可以随时
得到当前的事务并进行提交或者回滚操作.这个方法在以前版本的hibernate中是不存在
的.
Hibernate工具类主要包括以下功能:
(1)Hibernate的初始化操作
  这个功能不放在任何方法中,采用静态编码的处理方式,在对象的初始化的时候被
  调用一次就可以了.
(2)得到当前的配置信息
  这个方法可以得到当前的配置信息,以便于动态进行配置参数的修改.hibernate
  的配置信息只在Hibernate初始化的时候使用一次,在完成初始化之后对配置文件
  或者Configuration对象所做的修改将不会生效.
(3)得到SessionFactory对象的实例
  这个方法用于得到当前系统运行时的SessionFactory对象的实例,这个对象的实例
  对于整个系统而言是全局唯一的.
(4)释放各种资源
  这个方法用于终止Hibernate的报务后,释放各种Hibernate所使用的资源.虽然这个
  方法几乎不会用到,但对于申请资源的及时释放是每个程序应该掌握的基本原则.
(5)重建SessionFactory
  由于SessionFactory对于整个Hibernate应用是唯一的.并且是在Hibernate初始化
  之后建立好的,而且对于配置文件的修改也不会影响到已经初始化的SessionFactory
  对象.那么如何才能使修改的配置信息对Hibernate起作用呢.这就需要重建SessionFactory
  对象实例.
(6)拦截器注册
  用于注册拦截器并重建SessionFactory.
HibenateUtil.java
import javax.naming.InitialContext;
import javax.naming.NamingException;

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


/**
 * 基础的Hibernate辅助类,用于Hibernate的配置和启动。
 * <p>
 * 通过静态的初始化代码来读取Hibernate启动参数,并初始化
 * <tt>Configuration</tt>和<tt>SessionFactory</tt>对象。
 * <p>
 *
 * @author galaxy
 */
public class HibernateUtil 
{

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

    // 指定定义拦截器属性名
    private static final String INTERCEPTOR_CLASS = "hibernate.util.interceptor_class";

    // 静态Configuration和SessionFactory对象的实例(全局唯一的)
    private static Configuration configuration;
    private static SessionFactory sessionFactory;

    static 
    {


        // 从缺省的配置文件创建SessionFactory
        try 
        {

         // 创建默认的Configuration对象的实例
         // 如果你不使用JDK 5.0或者注释请使用new Configuration()
         // 来创建Configuration()对象的实例
            configuration = new Configuration();

            // 读取hibernate.properties或者hibernate.cfg.xml文件
            configuration.configure();

            // 如果在配置文件中配置了拦截器,那么将其设置到configuration对象中
            String interceptorName = configuration.getProperty(INTERCEPTOR_CLASS);
            if (interceptorName != null) 
            {


                Class interceptorClass =
                        HibernateUtil.class.getClassLoader().loadClass(interceptorName);
                Interceptor interceptor = (Interceptor)interceptorClass.newInstance();
                configuration.setInterceptor(interceptor);
            }

            if (configuration.getProperty(Environment.SESSION_FACTORY_NAME) != null) 
            {


                // 让Hibernate将SessionFacory绑定到JNDI
                configuration.buildSessionFactory();
            } 
            else 
            {

                // 使用静态变量来保持SessioFactory对象的实例
                sessionFactory = configuration.buildSessionFactory();
            }

        } 
        catch (Throwable ex) 
        {


            // 输出异常信息
            log.error("Building SessionFactory failed.", ex);
            ex.printStackTrace();
            throw new ExceptionInInitializerError(ex);
        }
    }

    /**
     * 返回原始的Configuration对象的实例
     *
     * @return Configuration
     */
    public static Configuration getConfiguration() 
    {


        return configuration;
    }

    /**
     * 返回全局的SessionFactory对象的实例
     *
     * @return SessionFactory
     */
    public static SessionFactory getSessionFactory() 
    {


        SessionFactory sf = null;
        String sfName = configuration.getProperty(Environment.SESSION_FACTORY_NAME);
        if ( sfName != null) 
        {

            log.debug("Looking up SessionFactory in JNDI.");
            try 
            {

                sf = (SessionFactory) new InitialContext().lookup(sfName);
            } 
            catch (NamingException ex) 
            {

                throw new RuntimeException(ex);
            }
        } 
        else 
        {

            sf = sessionFactory;
        }
        if (sf == null)
            throw new IllegalStateException( "SessionFactory not available." );
        return sf;
    }

    /**
     * 关闭当前的SessionFactory并且释放所有的资源
     */
    public static void shutdown() 
    {


        log.debug("Shutting down Hibernate.");
        // Close caches and connection pools
        getSessionFactory().close();

        // Clear static variables
        configuration = null;
        sessionFactory = null;
    }


    /**
     * 使用静态的Configuration对象来重新构建SessionFactory。
     */
     public static void rebuildSessionFactory() 
     {


        log.debug("Using current Configuration for rebuild.");
        rebuildSessionFactory(configuration);
     }

    /**
     * 使用指定的Configuration对象来重新构建SessionFactory对象。
     *
     * @param cfg
     */
     public static void rebuildSessionFactory(Configuration cfg) 
     {


        log.debug("Rebuilding the SessionFactory from given Configuration.");
        synchronized(sessionFactory) 
        {

            if (sessionFactory != null && !sessionFactory.isClosed())
                sessionFactory.close();
            if (cfg.getProperty(Environment.SESSION_FACTORY_NAME) != null)
                cfg.buildSessionFactory();
            else
                sessionFactory = cfg.buildSessionFactory();
            configuration = cfg;
        }
     }

    /**
     * 在当前SessionFactory中注册一个拦截器
     */
    public static SessionFactory registerInterceptorAndRebuild(Interceptor interceptor) 
    {


        log.debug("Setting new global Hibernate interceptor and restarting.");
        configuration.setInterceptor(interceptor);
        rebuildSessionFactory();
        return getSessionFactory();
    }

    /**
     * 获得拦截器对象
     * 
     * @return Interceptor
     */
    public static Interceptor getInterceptor() 
    {


        return configuration.getInterceptor();
    }

    /**
     * 提交当前事务,并开始一个新的事务
     */
    public static void commitAndBeginTransaction()
    {


     sessionFactory.getCurrentSession().getTransaction().commit();
     sessionFactory.getCurrentSession().beginTransaction();
    }
}

转载地址:http://sbhmi.baihongyu.com/

你可能感兴趣的文章
test-definitions/blob/master/auto-test/boost/boost.sh
查看>>
Java多态性理解
查看>>
Intellij Idea 工具在java文件中怎么避免 import .*包,以及import包顺序的问题
查看>>
IDEA Properties中文unicode转码问题
查看>>
Oracle中Blob转换成Clob
查看>>
Linux如何查看so中函数名
查看>>
自动管理代码的android.mk
查看>>
cocos2dx 2.2.6编译记录(1)
查看>>
makefile学习网站
查看>>
C 编写lua模块(1)
查看>>
Lua教程:Lua调用C/C++函数(4)
查看>>
win下创建win32控制台工程,执行lua脚本
查看>>
cocos2dx android启动错误
查看>>
eclipse: android rename package name
查看>>
cocos2dx c++调用java思想
查看>>
cocos2dx lua Node节点 私有数据存取
查看>>
lua math.ceil math.ceil
查看>>
cocos2dx CCNode计算node的大小
查看>>
cocos2dx 布局记录(1)
查看>>
lua 多行注释和取消多行注释
查看>>