1 package comum.database;
2
3 import org.hibernate.FlushMode;
4 import org.hibernate.HibernateException;
5 import org.hibernate.Session;
6 import org.hibernate.SessionFactory;
7 import org.hibernate.cfg.AnnotationConfiguration;
8 import org.hibernate.cfg.Configuration;
9
10
11
12
13
14
15 public class HibernateUtil {
16
17 private static final SessionFactory sessionFactory;
18 private static final ThreadLocal<Session> thread = new ThreadLocal<Session>();
19 private static Configuration configuration = null;
20
21 static {
22 try {
23 configuration = new AnnotationConfiguration().configure();
24 sessionFactory = configuration.buildSessionFactory();
25 } catch (HibernateException ex) {
26 throw new RuntimeException("Problema de configuraĆ§Ć£o: " + ex.getMessage());
27 } catch (Throwable t) {
28 t.printStackTrace();
29 throw new RuntimeException("Houve um problema ao carregar o HibernateUtil.");
30 }
31 }
32
33
34
35
36
37
38
39
40
41 public static Session currentSession() throws HibernateException {
42 Session s = thread.get();
43 if (s == null) {
44 s = sessionFactory.openSession();
45 s.setFlushMode(FlushMode.COMMIT);
46 thread.set(s);
47 }
48 return s;
49 }
50
51
52
53
54
55
56
57
58
59 public static void closeSession() throws HibernateException {
60 Session s = thread.get();
61 thread.set(null);
62 if (s != null) {
63 s.close();
64 }
65 }
66
67
68
69
70
71
72
73
74
75 public static void clearSession() throws HibernateException {
76 Session s = (Session) thread.get();
77 if (s != null) {
78 s.clear();
79 }
80 }
81
82
83
84
85
86
87
88
89
90 public static Configuration getConfiguration() {
91 return configuration;
92 }
93 }