miercuri, 3 iunie 2009

Hibernate session in web applications

In this article, I show a method in which we can avoid using EAGER fetch type in hibernate entities. For opening a hibernate session in web application we can use a filter that is mapped for /* url pattern. This filter will open a hibernate session and make it available for the current request. In this way, every Collection attribute from an entity can be easily accessed during the request. Some common problems met when not using this method is related to session being closed when trying to access an element from a collection. The session will be put as an request attribute and we call it OPENED_CONNECTION. The following code should give an idea of how we open and use a hibernate session in this way.

public class ManageConnection implements Filter {

private FilterConfig filterConfig;

public void destroy() {}

public void init(FilterConfig fConfig) {

this.filterConfig = fConfig;

}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

Object obj = request.getAttribute("OPENED_CONNECTION");

Session ses = null;

if(obj != null) {

ses = (Session)obj;

try {

ses.close();

}

catch(HibernateException ex) {

ex.printStackTrace(); //just print the stack trace into log files

}

}

ses = HibernateSingleton.getInstance().openSession();

request.setAttribute("OPENED_CONNECTION", ses);

chain.doFilter(request, response);

}

}


I use a helper class called HibernateSingleton. The code for this class is presented bellow:


public class HibernateSingleton {

private static SessionFactory sessionFactory;

static

{

sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();

}

public static SessionFactory getInstance()

{

return sessionFactory;

}

public static Session getRequestSession() {

return (Session)Contexts.getRequest().getAttribute("OPENED_CONNECTION");

}

}


Basically, the class build a Hibernate session factory and provides two static methods. One of them help as to get a Hibernate session instance. The other method returns the opened_connection attribute from the request. In my case Contexts.getRequest() method is just a wrapper method which has the code: return (HttpRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
Of course this is an example from a JSF application.
Now, everytime you need a hibernate session in your application you just use HibernateSingleton.getRequestSession() method. If you have used other methods for managing hibernate sessions you will definitely "love" this one. It also improves performance.

Niciun comentariu:

Trimiteți un comentariu