Hibernate的辅助类——HibernateUtil

来源:互联网 发布:边境杀手解析知乎 编辑:程序博客网 时间:2024/05/23 11:42

Hibernate辅助类是用来负责启动 Hibernate 和方便地操作org.hibernateSessionFactory

  1. import org.hibernate.SessionFactory;
  2. import org.hibernate.cfg.Configuration;
  3. public class HibernateUtil {
  4.     private static final SessionFactory sessionFactory ;
  5.     static{
  6.              // Create the SessionFactory from hibernate.cfg.xml
  7.            sessionFactory = new Configuration().configure().buildSessionFactory();
  8.      }
  9. private static SessionFactory buildSessionFactory() {
  10.                  return sessionFactory;
  11. }
  12.     public static SessionFactory getSessionFactory() {
  13.         return sessionFactory;
  14.     }
  15. }

       只要你持有 org.hibernate.SessionFactory,大可在任何时候、任何地点调用这个方法getCurrentSession() 方法

总会返回“当前的”工作单元session

Hibernate 提供三种跟踪当前会话的方法。基于“线程”的方法不适合于产品环境,它仅用于 prototyping 和教学用途。后面将更详细地讨论会话跟踪。

session的生命周期

     Session 在第一次被使用的时候,即第一次调用 getCurrentSession() 的时候,其生命周期就开始。然后它被 Hibernate 绑定到当前线程。当事务结束的时候,不管是提交还是回滚,Hibernate 会自动把org.hibernate.Session 从当前线程剥离,并且关闭它。假若你再次调用getCurrentSession(),你会得到一个新的org.hibernate.Session,并且开始一个新的工作单元。
        Hibernate org.hibernate.Session 的生命周期可以很灵活。绝对不要把应用程序设计成为每一次数据库操作都用一个新的 Hibernate org.hibernate.Session。

原创粉丝点击