使用Hibernate框架时创建获取Session和关闭Session的工具类

来源:互联网 发布:臻云创投投资人工智能 编辑:程序博客网 时间:2024/06/14 13:22

工具类代码如下:

package com.study.utils;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;import org.hibernate.cfg.Configuration;public class HibernateUtil {// 常量名全大写,而该常量一般用于外部使用,内部使用建议定义变量获取private static final String CONFIG_FILENAME = "/hibernate.cfg.xml";private static String configFile = CONFIG_FILENAME;private static Configuration cfg = new Configuration();// 创建Configuration对象private static StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();private static SessionFactory factory;//每个线程都有一个ThreadLocal类型的变量,可以用于存储表示本地线程中的数据private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();static {try {// 加载注册文件cfg.configure(configFile);// 创建SessionFactorybuilder.applySettings(cfg.getProperties());factory = cfg.buildSessionFactory(builder.build());} catch (Exception e) {System.out.println("SessionFactory error");e.printStackTrace();}}public static Session getSession() {Session session = threadLocal.get();//获取ThreadLocal变量中的数据if(session == null || !session.isOpen()){if(factory == null){buildSessionFactory();}// 打开session,预防factory到此处也并没有获取到(factory为null)session = (factory != null) ? factory.openSession() : null;//将session存入ThreadLocal变量threadLocal.set(session);}return session;}public static void buildSessionFactory(){try {// 加载注册文件cfg.configure(configFile);// 创建SessionFactorybuilder.applySettings(cfg.getProperties());factory = cfg.buildSessionFactory(builder.build());} catch (Exception e) {System.out.println("SessionFactory error");e.printStackTrace();}}public static void closeSession() throws HibernateException{Session session = threadLocal.get();//获取ThreadLocal变量中的数据threadLocal.set(null);if(session != null){session.close();}}}

创建工具类后,可以直接使用类名调用类中方法获取或者关闭Session:,如下:

获取Session:

Session session = HibernateUtil.getSession();
关闭Session:
HibernateUtil.closeSession();


0 0
原创粉丝点击