View Javadoc
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   * @author N/C
12   * @since N/C
13   * @version N/C
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  	 * Retorna sessao ativa.<br>
34  	 * 
35  	 * @author N/C
36  	 * @since N/C
37  	 * @version N/C
38  	 * @return Session
39  	 * @throws HibernateException
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  	 * Fecha a Sessao.<br>
53  	 * 
54  	 * @author N/C
55  	 * @since N/C
56  	 * @version N/C
57  	 * @throws HibernateException
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  	 * Limpa a sessao.<br>
69  	 * 
70  	 * @author N/C
71  	 * @since N/C
72  	 * @version N/C
73  	 * @throws HibernateException
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  	 * Retorna a Configuracao.<br>
84  	 * 
85  	 * @author N/C
86  	 * @since N/C
87  	 * @version N/C
88  	 * @return Configuration
89  	 */
90  	public static Configuration getConfiguration() {
91  		return configuration;
92  	}
93  }