首页 > 代码库 > hibernate中执行hql语句创建session需要的HibernateUtil类

hibernate中执行hql语句创建session需要的HibernateUtil类

import org.hibernate.HibernateException;  import org.hibernate.Session;  import org.hibernate.SessionFactory;  import org.hibernate.cfg.Configuration;    public class HibernateUtil {        private static SessionFactory sessionFactory = null;        static {          try {              Configuration cfg = new Configuration().configure();              sessionFactory = cfg.buildSessionFactory();          } catch (HibernateException e) {              // TODO: handle exception              e.printStackTrace();          }      }        public static SessionFactory getSessionFactory() {          return sessionFactory;      }        public static Session getSession() {          Session session = (sessionFactory != null) ? sessionFactory.openSession() : null;          return session;      }        public static void closeFactory(Session session) {          if (session != null) {              if (session.isOpen()) {                  session.close();              }          }      }  }  

1.这个工具类可以直接使用获取session(static方法) 但是需要注意的是这个类不是线程安全的 hibernate提倡用线程安全的工具类

2.具体过程可以理解为得到Configuration对象--->得到session工厂  sessionFactory--->获得session  openSession();最终调用session的各种方法进行数据操作。

3.可以参考hibernate文档 有非常详细的介绍 hibernate-distribution-3.3.2.GA\documentation\manual\zh-CN 中文版在document文件夹下

文档内容

1.1.6. 启动和辅助类

It is time to load and store some Event objects, but first you have to complete the setup with some infrastructure code. You have to startup Hibernate by building a global org.hibernate.SessionFactoryobject and storing it somewhere for easy access in application code. A org.hibernate.SessionFactory is used to obtain org.hibernate.Session instances. A org.hibernate.Session represents a single-threaded unit of work. The org.hibernate.SessionFactory is a thread-safe global object that is instantiated once.

We will create a HibernateUtil helper class that takes care of startup and makes accessing theorg.hibernate.SessionFactory more convenient.

package org.hibernate.tutorial.util;    import org.hibernate.SessionFactory;  import org.hibernate.cfg.Configuration;    public class HibernateUtil {        private static final SessionFactory sessionFactory = buildSessionFactory();        private static SessionFactory buildSessionFactory() {          try {              // Create the SessionFactory from hibernate.cfg.xml              return new Configuration().configure().buildSessionFactory();          }          catch (Throwable ex) {              // Make sure you log the exception, as it might be swallowed              System.err.println("Initial SessionFactory creation failed." + ex);              throw new ExceptionInInitializerError(ex);          }      }        public static SessionFactory getSessionFactory() {          return sessionFactory;      }    }