Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1899125
  • 博文数量: 606
  • 博客积分: 9991
  • 博客等级: 中将
  • 技术积分: 5725
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-17 19:07
文章分类

全部博文(606)

文章存档

2011年(10)

2010年(67)

2009年(155)

2008年(386)

分类:

2008-08-05 22:47:32

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的配置和启动。
 *


 * 通过静态的初始化代码来读取Hibernate启动参数,并初始化
 * ConfigurationSessionFactory对象。
 *


 *
 * @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();
    }
}

阅读(608) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~