SEVERE: could not initialize proxy - no Session
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
Pensava que usando o "Open Session in View" eu não estaria correndo esse risco já que a sessão deveria ser fechada depois da RENDER_RESPONSE ...
Dei várias lidas na documentação, mas não achei nada, gostaria de entender melhor como que funciona o "Open Session in View" ... onde devo criar uma sessão (abrir uma sessão) e onde devo fecha-la ?
public class HibernateSessionRequestFilter implements Filter {
private static Log log = LogFactory.getLog(HibernateSessionRequestFilter.class);
private SessionFactory sf;
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
try {
log.debug("Starting a database transaction");
sf.getCurrentSession().beginTransaction();
// Call the next filter (continue request processing)
chain.doFilter(request, response);
// Commit and cleanup
log.debug("Committing the database transaction");
sf.getCurrentSession().getTransaction().commit();
} catch (StaleObjectStateException staleEx) {
log.error("This interceptor does not implement optimistic concurrency control!");
log.error("Your application will not work until you add compensation actions!");
// Rollback, close everything, possibly compensate for any permanent changes
// during the conversation, and finally restart business conversation. Maybe
// give the user of the application a chance to merge some of his work with
// fresh data... what you do here depends on your applications design.
throw staleEx;
} catch (Throwable ex) {
// Rollback only
ex.printStackTrace();
try {
if (sf.getCurrentSession().getTransaction().isActive()) {
log.debug("Trying to rollback database transaction after exception");
sf.getCurrentSession().getTransaction().rollback();
}
} catch (Throwable rbEx) {
log.error("Could not rollback transaction after exception!", rbEx);
}
// Let others handle it... maybe another interceptor for exceptions?
throw new ServletException(ex);
}
}
public void init(FilterConfig filterConfig) throws ServletException {
log.debug("Initializing filter...");
log.debug("Obtaining SessionFactory from static HibernateUtil singleton");
sf = HibernateUtil.getSessionFactory();
}
public void destroy() {}
}
Primeiramente eu tentava abrir uma sessão e fecha-la dentro do proprio filtro fazendo isso:
try {
System.out.println("Buscando sessao!");
sf.openSession();
sf.getCurrentSession().beginTransaction();
// Call the next filter (continue request processing)
chain.doFilter(request, response);
// Commit and cleanup
sf.getCurrentSession().getTransaction().commit();
sf.getCurrentSession().close();
System.out.println("Comitando sessao");
} catch (StaleObjectStateException staleEx) {
//.... continua