Thursday, 26 September 2013

Open Session In View(OSIV)

Advertisement

Once the session is closed you can not be able to access the data from detached object and if you do you will get a LazyInitializationException: Session has been closed. It means that your session and session transaction is closed and you are trying to access the information from the proxy that is not initialized.
These are the solutions to overcome this LazyInitializationException :
  1. Open session in view.
  2. Thread local design pattern.
  3. Command design pattern.
  4. Long session
I will explain all of these in my next post but now we are going to talk about Open Session In View(OSIV).
To implement OSIV in your project you have to use filter that will open the session with every coming request and close the session after the JSP page is rendered to the client.

HibernateUtil

public class HibernateUtil {

static SessionFactory factory;

static {

Configuration cfg=new Configuration();

cfg=cfg.configure();

factory=cfg.buildSessionFactory();

}

public static SessionFactory getSessionFactory() {

System.out.println("factory: "+factory);

return factory;

}

}


In the above hibernateutil class you have static SessionFactory instance that will be initialized at the time of starting the server. So after starting the server you have an initialized instance of SessionFactory and you can get the object by using getter of this.

HFilter

public class HFilter implements Filter {

private SessionFactory sf;
@Override
public void doFilter(ServletRequest hreq, ServletResponse hres,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
try {
sf.getCurrentSession().beginTransaction();
chain.doFilter(hreq, hres);
sf.getCurrentSession().getTransaction().commit();
}
catch(Exception e) {
e.printStackTrace();
}
}

@Override
public void init(FilterConfig fc) throws ServletException {
// TODO Auto-generated method stub
sf=HibernateUtil.getSessionFactory();
}

@Override
public void destroy() {
// TODO Auto-generated method stub

}
}


Above you can see the servlet filter code that is responsible for managing the session. It will open the session on every incoming request and close the session after rendering the presentation page.
In the above code you can see that i used
sf.getCurrentSession().beginTransaction();

Here i didn't try to open and close the session i just used getCurrentSession() and begin the transaction on the session so you may question that who is responsible for opening and closing the session. Actually if you call getCurrentSession() then no need to open the session it will be initialized when you begin the transaction and closed when you commit the transaction.
So best of luck guy's.


EmoticonEmoticon