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

王朝学院·作者佚名  2016-05-29
窄屏简体版  字體: 小  |  中  |  大  |  超大  

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 someEventobjects, but first you have to complete the setup with some infrastructure code. You have to startup Hibernate by building a globalorg.hibernate.SessionFactoryobject and storing it somewhere for easy access in application code. Aorg.hibernate.SessionFactoryis used to obtainorg.hibernate.Sessioninstances. Aorg.hibernate.Sessionrepresents a single-threaded unit of work. Theorg.hibernate.SessionFactoryis a thread-safe global object that is instantiated once.

We will create aHibernateUtilhelper class that takes care of startup and makes accessing theorg.hibernate.SessionFactorymore 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; } }

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航