博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HibernateUtil
阅读量:6910 次
发布时间:2019-06-27

本文共 1953 字,大约阅读时间需要 6 分钟。

import org.hibernate.*; import org.hibernate.cfg.*; import org.hibernate.service.*; import org.hibernate.boot.registry.*; /**  * 该工具类提供了一个属性:SessionFactory sessionFactory  * 并创建了sessionFactory 将它设置成static 这样其他程序就可以直接通过此工具类引用  * 提供了二个方法:  * 1:通过线程创建Session-->currentSession()  * 2:关闭Session-->closeSession()  * 需要在主类中手动关闭sessionFactory  */ public class HibernateUtil {
public static final SessionFactory sessionFactory; //创建sessionFactory static {
try {
// 采用默认的hibernate.cfg.xml来启动一个Configuration的实例 Configuration cfg = new Configuration() .configure(); // 以Configuration实例来创建SessionFactory实例 ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(cfg.getProperties()).build(); sessionFactory = cfg.buildSessionFactory(serviceRegistry); } catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } // ThreadLocal可以隔离多个线程的数据共享,因此不再需要对线程同步 public static final ThreadLocal
session = new ThreadLocal
(); //创建Session public static Session currentSession() throws HibernateException {
//通过线程对象.get()方法安全创建Session Session s = session.get(); // 如果该线程还没有Session,则创建一个新的Session if (s == null) {
s = sessionFactory.openSession(); // 将获得的Session变量存储在ThreadLocal变量session里 session.set(s); } return s; } //关闭Session public static void closeSession() throws HibernateException {
Session s = session.get(); if (s != null) s.close(); session.set(null); } }

转载于:https://www.cnblogs.com/sgx0214/p/7566735.html

你可能感兴趣的文章
Hadoop Yarn REST API未授权漏洞利用挖矿分析
查看>>
asp.net Core 获取应用程序所在目录的2种方式
查看>>
Android震动vibrator(马达)--系统到驱动的流程【转】
查看>>
Linux下分布式系统以及CAP理论分析
查看>>
Oracle与Sql server的区别
查看>>
JavaScript 判断一个对象{}是否为空对象的简单方法
查看>>
C#使用Xamarin开发可移植移动应用(1.入门与Xamarin.Forms页面),附源码
查看>>
java 正则例子
查看>>
拆系数FFT
查看>>
SpringBoot乱码
查看>>
MySQL远程连接失败(错误码:2003)
查看>>
EMQ 注意事项
查看>>
安装SQL Server时,提示VS Shell 安装失败,退出代码为 1638。
查看>>
systemd实践: 依据情况自动重启服务【转】
查看>>
Spring Security教程(五):自定义过滤器从数据库从获取资源信息
查看>>
logstash配置
查看>>
什么样的数据分析工具才是营销人最想拥有的?
查看>>
cmp()
查看>>
Linux终端回话记录和回放工具 - asciinema使用总结
查看>>
《中國姓氏大全》【带拼音】
查看>>