-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 19 posts ]  Go to page 1, 2  Next
Author Message
 Post subject: Open Session in View Help!
PostPosted: Thu Jun 09, 2005 12:17 pm 
Newbie

Joined: Mon Jun 06, 2005 12:51 pm
Posts: 16
Hibernate version: 2.1.7
using tomcat 5.0.28
just jsp's and servlets

I've been trying to figure out how to use the "Open Session In View" pattern: http://www.hibernate.org/43.html

and I've read through that whole page and many fourms and still can't get this working!

anytime I try and load a jsp page I get the "LazyInitializationException - no session or session was closed"

Is there any good examples, that show the web.xml, the filter, and an example class that runs a query or something?

any help would be great.

- Zeb[/url]


Top
 Profile  
 
 Post subject:
PostPosted: Thu Jun 09, 2005 12:46 pm 
Regular
Regular

Joined: Thu May 26, 2005 2:08 pm
Posts: 99
FYI: Chapter 8 of "Hibernate in Action" covers this topic.


Top
 Profile  
 
 Post subject:
PostPosted: Thu Jun 09, 2005 1:14 pm 
Newbie

Joined: Mon Jun 06, 2005 12:51 pm
Posts: 16
Hey thanks I'm reading through it now.

I thought scaned through the book pretty good, I guess I just didn't see it.

- Zeb


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jun 10, 2005 11:16 am 
Newbie

Joined: Mon Jun 06, 2005 12:51 pm
Posts: 16
Ok, I thought I had it fuiured out, but I keep getting "net.sf.hibernate.LazyInitializationException: Failed to lazily initialize a collection - no session or session was closed" on my jsp page.
I'm using the HibernateUtil from caveatemptor and here is my filter:
Code:
    public class HibernateFilter implements Filter {
    private  Logger  logger  = Logger.getLogger(getClass());
   
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("Servlet filter init, now opening/closing a Session for each request.");
    }
   
    public void doFilter(ServletRequest request,
            ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        try {
            HibernateUtil.beginTransaction();
            Session hibSession = HibernateUtil.getSession();
           
            chain.doFilter(request, response);

            HibernateUtil.commitTransaction();
        } finally {
            HibernateUtil.closeSession();
        }
    }
   
    public void destroy() {}
   
}


I Redirect from a servlet to a jsp and I see part of the jsp display then I get that error.

This is really starting to bug me.

-Zeb


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jun 10, 2005 11:40 am 
Hibernate Team
Hibernate Team

Joined: Mon Aug 25, 2003 9:11 pm
Posts: 4592
Location: Switzerland
Do you know what a "log" is?


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jun 10, 2005 11:59 am 
Newbie

Joined: Mon Jun 06, 2005 12:51 pm
Posts: 16
No what's that?.....

I have logging setup every where, and I've narrowed it down to the line in my jsp that's causing this, but that doesen't really help me.

Code:
10 Jun 2005 10:49:47 -- us.wi.k12.madison.plp.helpers.HibernateUtil -- DEBUG -- Starting new database transaction in this thread.
10 Jun 2005 10:49:47 -- us.wi.k12.madison.plp.helpers.HibernateUtil -- DEBUG -- Opening new Session for this thread.
10 Jun 2005 10:49:47 -- us.wi.k12.madison.plp.servlets.PrepUserDefinedGoals -- DEBUG -- Starting doGet()
10 Jun 2005 10:49:47 -- us.wi.k12.madison.plp.servlets.PrepUserDefinedGoals -- DEBUG -- redirecting to page: /plp/users/myLearningStyleGoals
10 Jun 2005 10:49:47 -- us.wi.k12.madison.plp.helpers.HibernateUtil -- DEBUG -- Committing database transaction of this thread.
10 Jun 2005 10:49:47 -- us.wi.k12.madison.plp.helpers.HibernateUtil -- DEBUG -- Closing Session of this thread.
10 Jun 2005 10:49:47 -- us.wi.k12.madison.plp.helpers.HibernateUtil -- DEBUG -- Starting new database transaction in this thread.
10 Jun 2005 10:49:47 -- us.wi.k12.madison.plp.helpers.HibernateUtil -- DEBUG -- Opening new Session for this thread.
10 Jun 2005 10:49:49 -- learnStyleGoals.jsp -- DEBUG -- Loading Header
10 Jun 2005 10:49:49 -- learnStyleGoals.jsp -- DEBUG -- Loading Sidebar
10 Jun 2005 10:49:49 -- learnStyleGoals.jsp -- DEBUG -- Loading Main Content
10 Jun 2005 10:49:49 -- learnStyleGoals.jsp -- DEBUG -- Checking loginbean.user.studentLearningStyleLink
10 Jun 2005 10:49:49 -- net.sf.hibernate.LazyInitializationException <init>
SEVERE: Failed to lazily initialize a collection - no session or session was closed
net.sf.hibernate.LazyInitializationException: Failed to lazily initialize a collection - no session or session was closed
   at net.sf.hibernate.collection.PersistentCollection.initialize(PersistentCollection.java:214)
   at net.sf.hibernate.collection.PersistentCollection.read(PersistentCollection.java:71)
   at net.sf.hibernate.collection.Set.isEmpty(Set.java:114)
   at org.apache.commons.el.EmptyOperator.apply(EmptyOperator.java:134)
   at org.apache.commons.el.UnaryOperatorExpression.evaluate(UnaryOperatorExpression.java:163)
   at org.apache.commons.el.ExpressionEvaluatorImpl.evaluate(ExpressionEvaluatorImpl.java:263)
   at org.apache.commons.el.ExpressionEvaluatorImpl.evaluate(ExpressionEvaluatorImpl.java:190)
   at org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:899)
   at org.apache.jsp.learnStyleGoals_jsp._jspx_meth_c_when_0(learnStyleGoals_jsp.java:504)
   at org.apache.jsp.learnStyleGoals_jsp._jspx_meth_c_choose_0(learnStyleGoals_jsp.java:477)
   at org.apache.jsp.learnStyleGoals_jsp._jspService(learnStyleGoals_jsp.java:209)
   at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
        ........
10 Jun 2005 10:49:49 -- us.wi.k12.madison.plp.helpers.HibernateUtil -- DEBUG -- Closing Session of this thread.


here's the line in my jsp:
Code:
..........
<log:debug category="learnStyleGoals.jsp">Checking loginbean.user.studentLearningStyleLink</log:debug>
                        <c:choose>
                            <c:when test="${not empty loginbean.user.studentLearningStyleLink}">
                            <log:debug category="learnStyleGoals.jsp">loginbean.user.studentLearningStyleLink Is not empty</log:debug>
                                <c:forEach var="slsl" items="${loginbean.user.studentLearningStyleLink}">
.........


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jun 10, 2005 12:07 pm 
Hibernate Team
Hibernate Team

Joined: Mon Aug 25, 2003 9:11 pm
Posts: 4592
Location: Switzerland
So the Session is closed before the JSP is rendered. Your filter doesn't work for whatever reason.


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jun 10, 2005 12:15 pm 
Newbie

Joined: Mon Jun 06, 2005 12:51 pm
Posts: 16
looks to me Like it's still open.
So, no one knows what's wrong... that's great

I don't know if this would help but is there some way I can put a delay after the chain.doFilter() before closing the session?


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jun 10, 2005 2:14 pm 
Newbie

Joined: Mon Jun 06, 2005 12:51 pm
Posts: 16
Ok, I did some more debugging, it still doesent work but here's what's happening.

First I created a custom tag that calls:
HibernateUtil.beginTransaction();
Session hibSession = HibernateUtil.getSession();
and I put it just before the line in my jsp, and I still get an error.

Next removed the open and close session stuff from the filter, and added:
HibernateUtil.beginTransaction();
Session hibSession = HibernateUtil.getSession();
to my login servlet.
This worked, because I never close the session which needs to be done.

so next I just added the commit and close to the end of the loginServlet, the filter stuff is still disabled and the custom tag in the jsp is still there.
Now you'd think this work since the custom tag is reopening the session just before the jsp tries to acces anything (and according to my logs it's being opened fine), but I still get the session not open error.

Is there something wrong with my HibernateUtil?

HibernateUtil.java
Code:
public class HibernateUtil {
   
    private static Logger  logger  = Logger.getLogger("us.wi.k12.madison.plp.helpers.HibernateUtil");
   
    private static Configuration configuration;
    private static SessionFactory sessionFactory;
    private static final ThreadLocal threadSession = new ThreadLocal();
    private static final ThreadLocal threadTransaction = new ThreadLocal();
    private static final ThreadLocal threadInterceptor = new ThreadLocal();
   
    // Create the initial SessionFactory from the default configuration files
    static {
        logger.debug("Configuring SessionFactory....");
        try {
            configuration = new Configuration();
            configuration.configure("/S1016900.cfg.xml");
            sessionFactory = configuration.buildSessionFactory();
            logger.info("SessionFactory Configured.");
           
            // 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
            logger.error("Building SessionFactory failed.", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
   
    /**
     * Returns the SessionFactory used for this static class.
     *
     * @return SessionFactory
     */
    public static SessionFactory getSessionFactory() {
                /* Instead of a static variable, use JNDI:
                SessionFactory sessions = null;
                try {
                        Context ctx = new InitialContext();
                        String jndiName = "java:hibernate/HibernateFactory";
                        sessions = (SessionFactory)ctx.lookup(jndiName);
                } catch (NamingException ex) {
                        throw new InfrastructureException(ex);
                }
                return sessions;
                 */
        return sessionFactory;
    }
   
    /**
     * Returns the original Hibernate configuration.
     *
     * @return Configuration
     */
    public static Configuration getConfiguration() {
        return configuration;
    }
   
    /**
     * Rebuild the SessionFactory with the static Configuration.
     *
     */
    public static void rebuildSessionFactory()
    throws InfrastructureException {
        logger.debug("rebuilding SessionFactory!");
        synchronized(sessionFactory) {
            try {
                sessionFactory = getConfiguration().buildSessionFactory();
            } catch (Exception ex) {
                throw new InfrastructureException(ex);
            }
        }
    }
   
    /**
     * Rebuild the SessionFactory with the given Hibernate Configuration.
     *
     * @param cfg
     */
    public static void rebuildSessionFactory(Configuration cfg)
    throws InfrastructureException {
        logger.debug("rebuilding SessionFactory!");
        synchronized(sessionFactory) {
            try {
                sessionFactory = cfg.buildSessionFactory();
                configuration = cfg;
            } catch (Exception ex) {
                throw new InfrastructureException(ex);
            }
        }
    }
   
    /**
     * Retrieves the current Session local to the thread.
     * <p/>
     * If no Session is open, opens a new Session for the running thread.
     *
     * @return Session
     */
    public static Session getSession()
    throws InfrastructureException {
        Session s = (Session) threadSession.get();
        try {
            if (s == null) {
                logger.debug("Opening new Session for this thread.");
                if (getInterceptor() != null) {
                    logger.debug("Using interceptor: " + getInterceptor().getClass());
                    s = getSessionFactory().openSession(getInterceptor());
                } else {
                    s = getSessionFactory().openSession();
                }
                threadSession.set(s);
            }
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        }
        return s;
    }
   
    /**
     * Closes the Session local to the thread.
     */
    public static void closeSession()
    throws InfrastructureException {
        try {
            Session s = (Session) threadSession.get();
            threadSession.set(null);
            if (s != null && s.isOpen()) {
                logger.debug("Closing Session of this thread.");
                s.close();
            }
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        }
    }
   
    /**
     * Start a new database transaction.
     */
    public static void beginTransaction()
    throws InfrastructureException {
        Transaction tx = (Transaction) threadTransaction.get();
        try {
            if (tx == null) {
                logger.debug("Starting new database transaction in this thread.");
                tx = getSession().beginTransaction();
                threadTransaction.set(tx);
            }
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        }
    }
   
    /**
     * Commit the database transaction.
     */
    public static void commitTransaction()
    throws InfrastructureException {
        Transaction tx = (Transaction) threadTransaction.get();
        try {
            if ( tx != null && !tx.wasCommitted()
            && !tx.wasRolledBack() ) {
                logger.debug("Committing database transaction of this thread.");
                tx.commit();
            }
            threadTransaction.set(null);
        } catch (HibernateException ex) {
            rollbackTransaction();
            throw new InfrastructureException(ex);
        }
    }
   
    /**
     * Commit the database transaction.
     */
    public static void rollbackTransaction()
    throws InfrastructureException {
        Transaction tx = (Transaction) threadTransaction.get();
        try {
            threadTransaction.set(null);
            if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) {
                logger.debug("Tyring to rollback database transaction of this thread.");
                tx.rollback();
            }
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        } finally {
            closeSession();
        }
    }
   
    /**
     * Reconnects a Hibernate Session to the current Thread.
     *
     * @param session The Hibernate Session to be reconnected.
     */
    public static void reconnect(Session session)
    throws InfrastructureException {
        try {
            session.reconnect();
            threadSession.set(session);
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        }
    }
   
    /**
     * Disconnect and return Session from current Thread.
     *
     * @return Session the disconnected Session
     */
    public static Session disconnectSession()
    throws InfrastructureException {
       
        Session session = getSession();
        try {
            threadSession.set(null);
            if (session.isConnected() && session.isOpen())
                session.disconnect();
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        }
        return session;
    }
   
    /**
     * Register a Hibernate interceptor with the current thread.
     * <p>
     * Every Session opened is opened with this interceptor after
     * registration. Has no effect if the current Session of the
     * thread is already open, effective on next close()/getSession().
     */
    public static void registerInterceptor(Interceptor interceptor) {
        threadInterceptor.set(interceptor);
    }
   
    private static Interceptor getInterceptor() {
        Interceptor interceptor =
                (Interceptor) threadInterceptor.get();
        return interceptor;
    }
   
}


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jun 10, 2005 2:20 pm 
Expert
Expert

Joined: Mon Feb 14, 2005 12:32 pm
Posts: 609
Location: Atlanta, GA - USA
zwollner wrote:
looks to me Like it's still open.
So, no one knows what's wrong... that's great

I don't know if this would help but is there some way I can put a delay after the chain.doFilter() before closing the session?


Are you filtering on *.jsp ? If so it'll start a new session just prior to creating the page, and also on includes, and this is (probably) not what you want.

We're using Struts and filtering on the Action servlet and it works great.


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jun 10, 2005 2:24 pm 
Newbie

Joined: Mon Jun 06, 2005 12:51 pm
Posts: 16
I'm filtering on "/*", and now that I think about it probably isn't the best Idea.
but what should I filter on? I'd like to use struts, but I'm not allowed to for this project.


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jun 10, 2005 2:35 pm 
Expert
Expert

Joined: Mon Feb 14, 2005 12:32 pm
Posts: 609
Location: Atlanta, GA - USA
zwollner wrote:
I'm filtering on "/*", and now that I think about it probably isn't the best Idea.
but what should I filter on? I'd like to use struts, but I'm not allowed to for this project.


If you have a Controller servlet - Struts or otherwise - then filter on that. If you're requesting JSP's directly, you're going to have problems using a filter for session control. I haven't done it so I don't have any suggestions.


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jun 10, 2005 2:39 pm 
Newbie

Joined: Mon Jun 06, 2005 12:51 pm
Posts: 16
Yes, I'm requesting JSP's directly, does anyone know how to get around this issue?


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 13, 2005 9:59 am 
Newbie

Joined: Mon Jun 06, 2005 12:51 pm
Posts: 16
Is it possible to use the "Open Session In View" pattern without a controller servlet?

-Zeb


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 13, 2005 10:36 am 
CGLIB Developer
CGLIB Developer

Joined: Thu Aug 28, 2003 1:44 pm
Posts: 1217
Location: Vilnius, Lithuania
Yes, it must work in the same way.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 19 posts ]  Go to page 1, 2  Next

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.