forked from maxliaops/Java_Web_Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHibernateUtil.java
More file actions
58 lines (54 loc) · 1.3 KB
/
HibernateUtil.java
File metadata and controls
58 lines (54 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package test;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* Hibernate初始化类,用于获取Session、SessionFactory 及关闭Session
* @author Li Yong Qiang
*/
public class HibernateUtil {
// SessionFactory对象
private static SessionFactory factory = null;
// 静态块
static {
try {
// 加载Hibernate配置文件
Configuration cfg = new Configuration().configure();
// 实例化SessionFactory
factory = cfg.buildSessionFactory();
} catch (HibernateException e) {
e.printStackTrace();
}
}
/**
* 获取Session对象
* @return Session对象
*/
public static Session getSession() {
//如果SessionFacroty不为空,则开启Session
Session session = (factory != null) ? factory.openSession() : null;
return session;
}
/**
* 获取SessionFactory对象
* @return SessionFactory对象
*/
public static SessionFactory getSessionFactory() {
return factory;
}
/**
* 关闭Session
* @param session对象
*/
public static void closeSession(Session session) {
if (session != null) {
if (session.isOpen()) {
session.close(); // 关闭Session
}
}
}
public static void main(String[] args) {
System.out.println(getSessionFactory());
}
}