I am writing a web app which uses the HibernateUtil class from the new Caveat Emptor for Hibernate3.
I had to change a few things due to the HAR deployment (removed the building of a session factory as JBoss does this for you with a HAR).
But I am running into a problem with the getSession function. The only way I could get it to work is by pulling the current session from the JNDI context every time and forgetting about storing it in the ThreadLocal variable and I am not sure that this is efficient.
Before I made the change the first call would work fine but subsequent calls would throw an exception about the "owning session not being open".
I know Hibernate has the ability to track its own sessions now with getCurrentSession() anyone have any examples of how this works?
I am pretty new to the JBoss and Hibernate scene so it is probably something rather easy but I am just not seeing it.
Code:
******** Excerpts from HibernateUtil from new Caveat Emptor ******
static {
try {
//configuration = new AnnotationConfiguration();
//configuration = new Configuration();
//sessionFactory = configuration.configure().buildSessionFactory();
//We could also let Hibernate bind it to JNDI:
//configuration.configure().buildSessionFactory();
} catch (Throwable ex) {
//We have to catch Throwable, otherwise we will miss
//NoClassDefFoundError and other subclasses of Error
log.error("Building SessionFactory failed.", ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() throws DAOException {
/* Instead of a static variable, use JNDI: */
SessionFactory sessions = null;
try {
Context ctx = new InitialContext();
String jndiName = "java:/hibernate/SessionFactory";
sessions = (SessionFactory) ctx.lookup(jndiName);
} catch (NamingException ex) {
throw new DAOException(ex);
}
return sessions;
//return sessionFactory;
}
public static Session getSession()
throws DAOException {
Session s = (Session) threadSession.get();
try {
/*
if (s == null) {
log.debug("Opening new Session for this thread.");
if (getInterceptor() != null) {
log.debug("Using interceptor: " + getInterceptor().getClass());
s = getSessionFactory().openSession(getInterceptor());
} else {
s = getSessionFactory().openSession();
}
threadSession.set(s);
}
*/
s = getSessionFactory().openSession();
//threadSession.set(s);
} catch (HibernateException ex) {
throw new DAOException(ex);
}
return s;
}