使用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
- 使用Hibernate框架时创建获取Session和关闭Session的工具类
- Hibernate创建sessionFactory,session和关闭session的工具类
- 创建Hibernate获取Session的工具类
- Hibernate中SessionFactory的创建和Session的获取
- java 使用hibernate时创建session的辅助类
- Hibernate获取Session的超实用Util工具类
- 获取hibernate的Session
- hibernate的session的util的获取与关闭
- hibernate获取SESSION和SESSION CLEAR
- Hibernate框架Session类get()和load()的区别
- Hibernate中使用帮助类获取session
- hibernate Session的使用
- Hibernate session 的使用
- Hibernate的Session使用
- 使用 spring框架 获取 session
- 使用 spring框架 获取 session
- Hibernate 创建session的步骤
- hibernate延迟加载和session关闭问题
- Foundation框架
- 深入理解Hibernate中Iterate方法
- 购物车的实现原理
- MPI-2 并行IO的使用方法
- 实验3 Android UI(2)创建“手机信息页面”
- 使用Hibernate框架时创建获取Session和关闭Session的工具类
- 手机页面
- 查看centos系统swap占用情况
- root用户和普通用户的时区不一致的问题解决
- 死磕观察者模式(1)
- android开发http请求POST&GET封装工具
- 微信页面通过LocalID预览图片,getlocallmgdata
- Java实现单向链表和双向链表
- 云计算60篇值得收藏的干货文章,全在这里了!