powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / Hibernate3 Где обычно вызывают метод HibernateUtil.closeSession() ?
3 сообщений из 3, страница 1 из 1
Hibernate3 Где обычно вызывают метод HibernateUtil.closeSession() ?
    #33512278
Alexey Turn
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Раньше использовал sessionFactory, как bean в Spring. Сейчас хочу сделать ThreadLocal переменную session

Код: plaintext
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.
 import  org.hibernate.*;
 import  org.hibernate.cfg.*;
 public   class  HibernateUtil {
 private   static  Log log = LogFactory.getLog(HibernateUtil. class );
 private   static   final  SessionFactory sessionFactory;
 static  {
 try  {
// Create the SessionFactory
sessionFactory =  new  Configuration().configure().buildSessionFactory();
}  catch  (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
log.error("Initial SessionFactory creation failed.", ex);
 throw   new  ExceptionInInitializerError(ex);
}
}
 public   static   final  ThreadLocal session =  new  ThreadLocal();
 public   static  Session currentSession() {
Session s = (Session) session.get();
// Open a new Session, if this Thread has none yet
 if  (s ==  null ) {
s = sessionFactory.openSession();
session.set(s);
}
 return  s;
}
 public   static   void  closeSession() {
Session s = (Session) session.get();
 if  (s !=  null )
s.close();
session.set( null );
}
}

Обычно в DAO слое писал:

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
Session session   = sessionFactory.openSession();

 try 
{
///
}  finally  
{
   session.close();
 } 

ThreadLocal работает немного по другому. По хорошему хотелось бы вызывать метод HibernateUtil.currentSession() перед обработкой Request (Например в фильтре). И вызывать метод HibernateUtil.closeSession() после отраьотки сервлета и Request.forward(request,response) на jsp страницу. Если, к примеру на jsp страничке хотим использовать lazy init, то HibernateUtil.closeSession() должен стоять внизу каждой jsp страницы чтоли? Не понятно.
...
Рейтинг: 0 / 0
Hibernate3 Где обычно вызывают метод HibernateUtil.closeSession() ?
    #33513055
Фотография Denis Popov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Alexey TurnПо хорошему хотелось бы вызывать метод HibernateUtil.currentSession() перед обработкой Request (Например в фильтре). И вызывать метод HibernateUtil.closeSession() после отработки сервлета и Request.forward(request,response) на jsp страницу. Если, к примеру на jsp страничке хотим использовать lazy init, то HibernateUtil.closeSession() должен стоять внизу каждой jsp страницы чтоли? Не понятно.
Посмотри пример HibernateThreadFilter Но это еще не все:) ИМХО в случае lazy initialization может потребоваться держать сессию для всей бизнес-операции, которая может растянуться на несколько страниц, по-моему это называется session-per-conversation. Почитай http://www.hibernate.org/42.html#A9
...
Рейтинг: 0 / 0
Hibernate3 Где обычно вызывают метод HibernateUtil.closeSession() ?
    #33513406
Andrew Bykov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Я юзаю session и transaction в ThreadLocal так:

Код: plaintext
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.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
 public   class  HibernateUtil {
     private   static  Logger logger = Logger.getLogger(HibernateUtil. class );
     private   static   final  SessionFactory sessionFactory;
     public   static   final  ThreadLocal session =  new  ThreadLocal();
     public   static   final  ThreadLocal transaction =  new  ThreadLocal();

    // Session factory initialization
     static  {
         try  {
            sessionFactory =  new  Configuration().configure("/hibernate.cfg.xml").buildSessionFactory();
//            sessionFactory = new Configuration().configure("/console.hibernate.cfg.xml").buildSessionFactory();
        }  catch  (HibernateException ex) {
             throw   new  RuntimeException("Configuration problem: " + ex.getMessage(), ex);
        }
    }


    /**
     * Get current Hibernate session or initialize it if it's null
     * @return Hibernate session instance
     */
     public   static  Session currentSession() {
        Session s = (Session) session.get();
        // Open a new Session, if this Thread has none yet
         try  {
             if  (s ==  null ) {
                s = sessionFactory.openSession();
                session.set(s);
            }
        }  catch  (HibernateException e) {
            logger.error("Get current session error: " + e.getMessage());
        }
         return  s;
    }

    /**
     * Close current Hibernate session
     */
     public   static   void  closeSession() {
        Session s = (Session) session.get();
        session.set( null );
         try  {
             if  (s !=  null )
                s.close();
        }  catch  (HibernateException e) {
            logger.error("Close current session error: " + e.getMessage());
        }
    }

    /**
     * Begin Hibernate transaction
     */
     public   static   void  beginTransaction() {
        Transaction tx = (Transaction) transaction.get();
         try  {
             if  (tx ==  null ) {
                tx = currentSession().beginTransaction();
                transaction.set(tx);
            }
        }  catch  (HibernateException e) {
            logger.error("Begin transaction error: " + e.getMessage());
        }
    }

    /**
     * Commit Hibernate transaction
     */
     public   static   void  commitTransaction() {
        Transaction tx = (Transaction) transaction.get();
         try  {
             if  (tx !=  null  && !tx.wasCommitted() && !tx.wasRolledBack()) {
                tx.commit();
            }
            transaction.set( null );
        }  catch  (HibernateException e) {
            rollbackTransaction();
            logger.error("Commit transaction error: " + e.getMessage());
        }
    }

    /**
     * Rollback Hibernate transaction
     */
     public   static   void  rollbackTransaction() {
        Transaction tx = (Transaction) transaction.get();
         try  {
            transaction.set( null );
             if  (tx !=  null  && !tx.wasCommitted() && !tx.wasRolledBack()) {
                tx.rollback();
            }
        }  catch  (HibernateException e) {
            logger.error("Rollback transaction error: " + e.getMessage());
        }  finally  {
            closeSession();
        }
    }
}
Сессии закрываю в фильтре после каждого реквеста
Код: plaintext
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.
 public   class  HibernateFilter  implements  Filter {
     private   static  Logger logger = Logger.getLogger(HibernateFilter. class );


    /**
     * Commit Hibernate transaction and close Hibernate session at the end of request  
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
     public   void  doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
             throws  IOException, ServletException {

         try  {
            chain.doFilter(request, response);
            HibernateUtil.commitTransaction();
        }  catch  (IOException e) {
            logger.debug("HibernateFilter error: " + e.getMessage());
        }  catch  (ServletException e) {
            logger.debug("HibernateFilter error: " + e.getMessage());
        }  finally  {
            HibernateUtil.closeSession();
            logger.debug("Hibernate filter: session closed");
        }
    }

     public   void  init(FilterConfig filterConfig)  throws  ServletException {
    }

     public   void  destroy() {
    }
}
Соответственно не забудь прописать в веб.хмл его
Код: plaintext
1.
2.
3.
4.
  <filter>
        <filter-name>HibernateFilter</filter-name>
        <filter- class >filters.HibernateFilter</filter- class >
    </filter>
...
Рейтинг: 0 / 0
3 сообщений из 3, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Hibernate3 Где обычно вызывают метод HibernateUtil.closeSession() ?
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]