Ray da Costa

« Conectar em EJB fora de EAR | Home | Commando -Dfile.encoding para JNPL »

Exemplo de SessionFactory com Hibernete

de raydacosta | Sexta, 26 de Setembro de 2008

1. package br.com.fts.util;
2.
3. import org.hibernate.*;
4. import org.hibernate.cfg.*;
5.
6. public class ConnectionFactory {
7.
8. private static final SessionFactory sessionFactory;
9.
10. public static final ThreadLocal session = new ThreadLocal();
11.
12. static {
13. try {
14. Configuration cfg = new Configuration();
15. cfg.configure("/hibernate.cfg.xml");
16. sessionFactory = cfg.buildSessionFactory();
17. } catch (MappingException e) {
18. System.err.println("Mapping Exception" + e.getMessage());
19. throw new RuntimeException(e);
20. } catch (HibernateException e) {
21. System.err.println("Hibernate Exception" + e.getMessage());
22. throw new RuntimeException(e);
23. }
24. }
25.
26. public static Session currentSession() {
27. Session s = (Session) session.get();
28. if (s == null) {
29. s = sessionFactory.openSession();
30. session.set(s);
31. }
32. return s;
33. }
34.
35. public static void closeSession() {
36. Session s = (Session) session.get();
37. if (s != null)
38. s.close();
39. session.set(null);
40. }
41.
42. }

Categorias: Sem Categoria, J2EE |  | Enviar por e-mail  | Hits para esta publicação: 224

Deixe uma resposta.