I've implemented Session in View pattern to enable lazy load in DAO pattern.
Then, some part, the lazy load is very ok, but at few other, i catch this error at the bottom of the display page :
.....
net.sf.hibernate.LazyInitializationException: Failed to lazily initialize a collection
....
Caused by:
java.lang.NullPointerException
at net.sf.hibernate.impl.SessionImpl.initializeCollection(SessionImpl.java:3259)
at net.sf.hibernate.collection.PersistentCollection.initialize(PersistentCollection.java:195)
... 45 more
So, can somebody here gives me an advise of what kind of this problem is ??
Thanks for reading..
PS: i'm using the latest hibernate version.
The implement of sessionfactory, i used the same as the follow
Code:
package de.gloegl.road2hibernate.util;
import java.io.*;
import javax.servlet.*;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.cfg.Configuration;
public class SessionManager implements Filter
{
protected static ThreadLocal hibernateHolder = new ThreadLocal();
protected static ThreadLocal txHolder = new ThreadLocal();
protected static SessionFactory factory;
public void init(FilterConfig filterConfig) throws ServletException
{
// Initialize hibernate
try
{
factory = new Configuration().configure().buildSessionFactory();
}
catch (HibernateException ex) { throw new ServletException(ex); }
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
if (hibernateHolder.get() != null)
throw new IllegalStateException(
"A session is already associated with this thread! "
+ "Someone must have called getSession() outside of the context "
+ "of a servlet request.");
try
{
chain.doFilter(request, response);
}
finally
{
Session sess = (Session)hibernateHolder.get();
Transaction tx = (Transaction)txHolder.get();
if (sess != null)
{
hibernateHolder.set(null);
try
{
if (tx != null) {
tx.commit();
}
sess.close();
}
catch (HibernateException ex) { throw new ServletException(ex); }
}
}
}
public static Session getSession() throws HibernateException
{
Session sess = (Session)hibernateHolder.get();
Transaction tx = (Transaction)txHolder.get();
if (sess == null)
{
sess = factory.openSession();
txHolder.set(sess.beginTransaction());
hibernateHolder.set(sess);
} else {
if (tx == null) {
throw new IllegalStateException("Transaction was allready rolled back");
}
}
return sess;
}
public static void rollback() throws HibernateException {
Transaction tx = (Transaction)txHolder.get();
if (tx == null) {
throw new IllegalStateException("Transaction was allready rolled back");
}
tx.rollback();
txHolder.set(null);
}
public void destroy() {
try {
factory.close();
}
catch (HibernateException ex) { throw new RuntimeException(ex); }
}
}