---
title: "封装HibernateUtil对象，方便的工具类（转）"
author: "/ty瑞克"
date: "2010-09-14T16:41:08Z"
tags: []
categories: ["企业架构"]
slug: "hibernateutil"
draft: false
lastmod: "2010-09-14T16:41:08Z"
id: 763146
url: "https://crazy4j.iteye.com/blog/763146"
---

01. **package** org.cric.util;
02. **import** org.hibernate.Session;
03. **import** org.hibernate.SessionFactory;
04. **import** org.hibernate.cfg.Configuration;
05. **public** **class** HibernateUtil {
06. **private** **static** SessionFactory factory;
07. **static**{//只创建一次，单实例
08. **try**{
09. //实例化Configuration对象,configure()方法,默认加载hibernate.hbm.xml文件
10. Configuration cfg=**new** Configuration().configure();
11. //虚拟数据库
12. factory=cfg.buildSessionFactory();
13. }**catch**(Exception e){
14. e.printStackTrace();
15. }
16. }
17. **public** **static** SessionFactory getSessionFactory(){//获取SessionFactory对象
18. **return** factory;
19. }
20. **public** **static** Session getSession(){//获取Session对象
21. **return** factory.openSession();
22. }
23. **public** **static** **void** closeSession(Session session){//关闭Session,因为Session不是线程安全的！
24. //线程安全是指多个线程并发时,线程之间不会相互影响
25. //比如,在多个线程同时操作对象的某个实例变量时,就回出现不正确的现象
26. **if**(session!=**null**){
27. **if**(session.isOpen()){
28. session.close();
29. }
30. }
31. }
32. }