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