-->
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.  [ 6 posts ] 
Author Message
 Post subject: OpenSessionInViewInterceptor configuration
PostPosted: Tue Mar 23, 2004 11:39 am 
Beginner
Beginner

Joined: Tue Nov 18, 2003 10:16 am
Posts: 33
Location: Cluj-Napoca, Romania
I using Hibernate/Spring for managing persistence/transactions and I want to use OpenSessionInViewInterceptor or OpenSessionInViewFilter to lazy-load Domain objects on the web tier.

My problem is that I didn't find any examples with this features.

Can anybody help me?

Best regards, Florin Marcus


Top
 Profile  
 
 Post subject:
PostPosted: Tue Mar 23, 2004 1:53 pm 
Regular
Regular

Joined: Wed Mar 03, 2004 9:38 am
Posts: 70
For the filter, put the lines

Code:
<filter>
    <filter-name>HibernateFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate.support.OpenSessionInViewFilter</filter-class>
</filter>


in your web.xml. Additionally, you need to map the filter to some servlet or url pattern, e.g

Code:
<filter-mapping>
    <filter-name>HibernateFilter</filter-name>
    <servlet-name>action</servlet-name>
</filter-mapping>


if you use struts and you call your struts servlet "action".

I haven't used the interceptor, but my understanding is that it is configured in the spring config files and not in web.xml. If you use spring mvc then the interceptor is probably a better choice for you.


Top
 Profile  
 
 Post subject:
PostPosted: Wed Mar 24, 2004 2:54 am 
Beginner
Beginner

Joined: Tue Nov 18, 2003 10:16 am
Posts: 33
Location: Cluj-Napoca, Romania
Thank you for response!

I am using Struts as a web layer, but because I use unit testing for business logic, is preferable to create lazy loading without tight coupling this mechanism to web layer.
Is very important that I can test the functionality of the application from unit tests.

That's why I prefer to use an Interceptor instead of a Http Filter.


Top
 Profile  
 
 Post subject:
PostPosted: Wed Mar 24, 2004 5:04 am 
Regular
Regular

Joined: Wed Mar 03, 2004 9:38 am
Posts: 70
You can use unit testing and lazy loading by explicitly opening a session in the setup code, follow the guidelines in this thread:

[url]
http://forum.hibernate.org/viewtopic.ph ... highlight=
[/url]


Top
 Profile  
 
 Post subject:
PostPosted: Wed Mar 24, 2004 7:16 am 
Beginner
Beginner

Joined: Tue Nov 18, 2003 10:16 am
Posts: 33
Location: Cluj-Napoca, Romania
Many thanks!

That really helped!


Top
 Profile  
 
 Post subject: Or you can use a timeout in unit testing
PostPosted: Wed Mar 24, 2004 11:27 pm 
Beginner
Beginner

Joined: Mon Mar 22, 2004 9:37 am
Posts: 22
Location: Willow Grove, PA
This is slightly modified from what is on the wiki
This should close a session after a timeout/or when thread dies. Note each query resets the timeout.

Code:
package com.diamondip.netcontrol.db;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.JDBCException;
import net.sf.hibernate.MappingException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;



public class HibernateSession {
    public static final ThreadLocal session = new ThreadLocal();
    Session hibernateSession;
    private static SessionFactory sf = null;
    ApplicationContext ctx = null;
    private static Log log = LogFactory.getLog(ServiceLocator.class);   
   
    private static HibernateSession me;
   
    static {
      try
      {
         me = new HibernateSession();
      }
      catch (Exception e)
      {
         log.fatal("Error occurred initializing ServiceLocator");
         e.printStackTrace();
      }
   }
   
   
//  ~ Constructors ===========================================================

    private HibernateSession() throws HibernateException, JDBCException {
       // Try to lookup a JNDI Connection
       try {
          
          sf = HibernateSession.createConfiguration();
        
          
          if (sf == null) {
              System.out.println("session factory is null in after create config");
           }
          
          
       } catch (MappingException me) {
          if (log.isDebugEnabled()) {
             log.info("error communicating with JNDI, assuming testcase");
          }

       }
    }
   
   
    public static Session currentSession() throws ServiceException {

        Session s = (Session) session.get();
        if (s == null) {
            //SessionFactory sf;
            try {
               // sf = (SessionFactory) new InitialContext().lookup("SessionFactory");
                s = sf.openSession();
               
            } catch (HibernateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                throw new ServiceException(e);
            }
            s = (Session) createSession(s,50 * 1000); //50 sec
            session.set(s);
        }
        return s;
    }

    public static void closeSession() throws HibernateException {
        Session s = (Session) session.get();
        session.set(null);
     
        if (s != null){
       
            if (s.isOpen())
         {
            s.flush();
            s.close();

            if (log.isDebugEnabled())
            {
               log.debug("Closed hibernate session.");
            }
         }
        }
    }
   
    /**
     * The classes with mappings to add to the Configuration are enumerated here.
     * There should be a "${class}.hbm.xml" mapping file for each class
     * stored with each compiled class file.
     * <p>
     * To complete the Hibernate setup, there must be a valid "hibernate.properties"
     * file under the "classes" folder (root of the classpath),
     * which specifies the details of the database hookup.
     * <p>
     * The mapping documents and properties file is all that Hibernate requires.
     * <p>
     * @return A Configuration object
     * @throws net.sf.hibernate.MappingException if any the mapping documents can be rendered.
     */
    private static final SessionFactory createConfiguration() throws MappingException, HibernateException {
       log.info(" Hibernate plugIn configuration loaded");
      
     /* Perhaps these classes can be loaded from the config files instead of specifying them here
      */
      
      ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
   
    return ((SessionFactory) ctx.getBean("sessionFactory"));

     }
   
       
    private static Session createSession(final Session hibernate, final long timeout) {
        return (Session)Proxy.newProxyInstance(Session.class.getClassLoader(),
                    new Class[] { Session.class },
                    new InvocationHandler () {
                        Session _hibernate = hibernate;
                        TimerTask t = null;
                        Timer timer = null;
                       
                        private void renewLease() {
                            System.out.println("renew called");
                            if (timer != null) {
                                timer.cancel();
                                System.out.println("cancel timer:" + timer);
                            }
                            timer = new Timer();
                            t = new TimerTask() {
                                public void run() {
                                    try {
                                        //run session close....
                                        closeSession();
                                    } catch (HibernateException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                }
                               
                            };
                            timer.schedule(t,timeout);
                        }
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            if (method.getName().equals("close")) {
                                //cancel the timer;
                                if (timer != null) {
                                    timer.cancel();
                                    return method.invoke(_hibernate,args);
                                }
                            }
                            renewLease();
                            return method.invoke(_hibernate,args);
                        }
                    });
        }
    }


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 

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.