How to initialize hibernate session from within servlet?
hibernate, java, servlets
Solution
There are a lot of ways how to manage hibernate session. One of the most common way is using `HibernateUtil` class. The usual implementation is, the `SessionFactory` is statically initialized, which means, the initialization will only be done once (when the class is loaded). Then it exposes a static method for getting the built `SessionFactory` instance. Here is an example of implementation from dzone.
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
For opening and closing of session, it is usually treated as a one unit with the request processing, so you call `HibernateUtil.getSessionFactory().openSession()` in the beginning of `doGet` or `doPost` and ensure to close the session before the end of the method.
Problem
I'm learning java servlets and hibernate. I have separate working examples of each and am now trying to merge the hibernate example into an http servlet. My simple hibernate sample starts with this code ``` factory = new AnnotationConfiguration().configure().buildSessionFactory(); Session session = factory.openSession(); ``` When the http servlet is called via an http get, I understand it's calling the constructor first, then the doGet method. Now my question (please be easy on me as I'm a newbie here): what is the accepted way to call the hibernate initialization code from the servlet? Do I put the above initialization code in the constructor method?