Hello All,
I have a web project that use servlets struts hibernate DAOs
I want to know where is the proper place to handle the session opening and closing
servlets , or struts action or DAOS or where exactly
I use this hibernate session factory
Code:
import java.util.Date;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
private static final ThreadLocal threadLocal = new ThreadLocal();
private static final SessionFactory sessionFactory;
public static Session getSession() throws HibernateException {
Session session = (Session)threadLocal.get();
if (session == null || !session.isOpen()) {
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
public static Session getNewSession() throws HibernateException {
Session session = sessionFactory.openSession();
return session;
}
public static void closeSession(Session session) {
clearSession(session);
session.close();
}
public static void closeSession() {
Session session = getSession();
closeSession(session);
}
public static void clearSession(Session session) {
session.flush();
session.clear();
}
public static void clearSession() {
Session session = getSession();
clearSession(session);
}
static {
try {
System.out.println("-------Create the SessionFactory from hibernate.cfg.xml-------From Source Code");
sessionFactory = (new Configuration()).configure("model/hibernate/config/hibernate.cfg.xml").buildSessionFactory();
}
catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
}