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 someEvent
objects, but first you have to complete the setup with some infrastructure code. You have to startup Hibernate by building a globalorg.hibernate.SessionFactory
object and storing it somewhere for easy access in application code. Aorg.hibernate.SessionFactory
is used to obtainorg.hibernate.Session
instances. Aorg.hibernate.Session
represents a single-threaded unit of work. Theorg.hibernate.SessionFactory
is a thread-safe global object that is instantiated once.
We will create aHibernateUtil
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; } }
新闻热点
疑难解答