Hibernate session management -


i'm using hibernate , have trouble in how use session, best method :

  1. use 1 session , open in singleton

    public static commonserviceimpl getinstance() {      if (session == null ||  !session.isopen() ) {         session = sessionfactory.opensession();     }     //session.clear();     return instance; } 
  2. use sessionfactory each time when wanna use session sessionfactory.getcurrentsession() ?

the session object designed lightweight, disposable object can open , dispose on demand.. should not try reuse on own (like singleton)
real problem thread safety: while sessionfactory object thread safe, session object not , cause havoc when pointed several threads.
if don't want open new session every time can use current session option allows bind session specific context (like thread) within session factory , retrieve each time..


Comments