-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJavaUtils-HibernateSessionFactory.template
executable file
·56 lines (46 loc) · 1.51 KB
/
JavaUtils-HibernateSessionFactory.template
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
package com.sd.packagename.common.util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* @Created with Atom
* @author @author@
* @time @now@
* @description
* Hibernate Session Factory 工具类
*
**/
public class HibernateSessionFactory {
private static final SessionFactory sessionFactory;
//使用ThreadLocal管理Session
private static final ThreadLocal < Session > threadLocal = new ThreadLocal < Session > ();
static {
try {
//根据hibernate.cfg.xml建立SessionFactory
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
ex.printStackTrace();
System.err.println("建立SessionFactory错误" + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return (sessionFactory);
}
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if ((session == null) || !session.isOpen()) {
session = (sessionFactory != null) ? sessionFactory.openSession() : null;
threadLocal.set(session);
}
return (session);
}
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null && session.isOpen()) {
session.close();
}
}
}