一个简单的Hibernate工具类HibernateUtil
HibernateUtil
1 package com.wj.app.util; 2 3 import org.hibernate.Session; 4 import org.hibernate.SessionFactory; 5 import org.hibernate.cfg.Configuration; 6 import org.hibernate.service.ServiceRegistry; 7 import org.hibernate.service.ServiceRegistryBuilder; 8 9 public class HibernateUtil { 10 public static final SessionFactory sessionFactory; 11 //ThreadLocal可以隔离多个线程的数据共享,因此不需要对线程进行同步 12 public static ThreadLocal<Session> session = new ThreadLocal<Session>(); 13 static 14 { 15 //使用默认配置文件创建Configuration实例 16 Configuration cfg = new Configuration() 17 .configure(); 18 19 //以Configuration实例来创建SessionFactory实例 20 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder() 21 .applySettings(cfg.getProperties()) 22 .buildServiceRegistry(); 23 24 /*ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() 25 .applySettings(cfg.getProperties()).build();*/ 26 27 sessionFactory = cfg.buildSessionFactory(serviceRegistry); 28 } 29 public static Session currentSession() { 30 31 Session s = session.get(); 32 //如果该线程还没有Session,则创建一个新的Session 33 if (s == null) 34 { 35 s = sessionFactory.openSession(); 36 //将获得的Session变量存储在ThreadLocal变量session里 37 session.set(s); 38 } 39 return s; 40 } 41 42 public static void clossSession() { 43 Session s = session.get(); 44 if (s != null) 45 { 46 s.close(); 47 } 48 session.set(null); 49 } 50 }
本博客文章皆出于学习目的,个人总结或摘抄整理自网络。引用参考部分在文章中都有原文链接,如疏忽未给出请联系本人。另外,作为一名菜鸟程序媛,如文章内容有错误,欢迎点击博客右上方的扣扣链接指导交流。