Announcement Announcement Module
Collapse
No announcement yet.
Getting different Sessions-Objects with OSIV Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Getting different Sessions-Objects with OSIV

    I have a problem implementinmg OSIV right.
    I am using GenericDAO with OSIV, and a SessionFactory.
    Everytime getSession in a DAO is called during the same request, a different Session Object is used and I dont know why. Normally the SessionFactory should prevent this, right? (Every operation within the DAO's calls get Session e.g. to create criteria).

    This is what my getSession() Method in the DAO looks like:
    Code:
    	protected Session getSession() {
    		if (session == null || !session.isOpen()){
    			logger.info("Session not set or closed");
    			try{
    				this.session = sessionFactory.getCurrentSession();
    				logger.info("SessionFactory: "+sessionFactory.hashCode());
    				logger.info("CurrentSession: "+session.hashCode());
    			} catch (NullPointerException e) {
    				logger.error("SessionFactory nicht gesetz!");
    				throw new IllegalStateException("Session has not been set on DAO before usage");
    
    			}
    		}
    		return session;
    	}
    The logged hashcode from the SessionFactory is always the same, but different for every Session.

    ApplicationContext (some parts are stripped):
    Code:
    	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    		<property name="dataSource">
    			<ref local="dataSource" />
    		</property>
    		<property name="hibernateProperties">
    			<props>
    				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
    				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
    				<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
    		 
    				<prop key="hibernate.c3p0.max_size">${hibernate.c3p0.max_size}</prop>
    				<prop key="hibernate.c3p0.max_size">${hibernate.c3p0.max_size}</prop>
    				<prop key="hibernate.c3p0.min_size">${hibernate.c3p0.min_size}</prop>
    				<prop key="hibernate.c3p0.timeout">${hibernate.c3p0.timeout}</prop>
    				<prop key="hibernate.c3p0.max_statements">${hibernate.c3p0.max_statements}</prop>
    				<prop key="hibernate.c3p0.idle_test_period">${hibernate.c3p0.idle_test_period}</prop>
    				<prop key="hibernate.c3p0.acquire_increment">${hibernate.c3p0.acquire_increment}</prop>
    				
    				<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
    				<prop key="hibernate.cache.use_query_cache">false</prop>
    				<prop key="hibernate.max_fetch_depth">10</prop>				
    				<prop key="hibernate.jdbc.batch_versioned_data">true</prop>
    				<prop key="hibernate.jdbc.use_streams_for_binary">true</prop>								
    			</props>
    		</property>
    		<property name="mappingResources">
    			<list>
    				<value>de/itservices/kp/common/persistence/mapping/Ansprechpartner.hbm.xml</value>
    				<value>de/itservices/kp/common/persistence/mapping/Geschaeftspartner.hbm.xml</value>
    				<value>de/itservices/kp/common/persistence/mapping/Standort.hbm.xml</value>
    				<value>de/itservices/kp/common/persistence/mapping/Anschrift.hbm.xml</value>
    				<value>de/itservices/kp/common/persistence/mapping/GeschaeftspartnerAnschrift.hbm.xml</value>
    				<value>de/itservices/kp/common/persistence/mapping/Bankverbindung.hbm.xml</value>
    				<value>de/itservices/kp/common/persistence/mapping/Ereignis.hbm.xml</value>
    			
    			</list>
    		</property>
    	</bean>
    
    		<bean id="geschaeftspartnerDAO" class="app.dao.impl.GeschaeftspartnerDAOHibernate" scope="singleton" >
    			<property name="sessionFactory" ref="sessionFactory" />			
    		</bean>
    
    		<bean id="standortAdministration" class="app.administration.StandortAdministration" scope="singleton">
    			<property name="standortDAO" ref="standortDAO" />	
    	</bean>
    Here is the definition of the OSIV-Filter in web.xml:
    Code:
    ...
    	<filter>
    		<description>
    			Implementierung des OpenSessionInView-Pattern.
    			Funktioniert, warum auch immer, nur mit Mapping auf die Request-URL.
    			Mapping auf das FacesServlet führt scheinbar dazu, dass der Filter nicht aufgerufen wird.
    		</description>
    		<filter-name>HibernateSessionFilter</filter-name>
    		<filter-class>
    			org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    		</filter-class>
    		<init-param>
    			<param-name>sessionFactoryBeanName</param-name>
    			<param-value>sessionFactory</param-value>
    		</init-param>
    	</filter>
    	<filter-mapping>
    		<filter-name>HibernateSessionFilter</filter-name>
    		<servlet-name>Persistent Faces Servlet</servlet-name>
    	</filter-mapping>
    
    	<!-- ICEFaces Servlets -->
    	<servlet>
    		<servlet-name>Persistent Faces Servlet</servlet-name>
    		<servlet-class>
    			com.icesoft.faces.webapp.xmlhttp.PersistentFacesServlet
    		</servlet-class>
    		<load-on-startup>1</load-on-startup>
    	</servlet>
    ...
    There are no exceptions during startup of Tomcat, so I excpect everything to be configured correct, at least syntactically.

    Is there any fault in wiring-up the components?

    Environment:
    Tomcat 6.x
    ICEfaces 1.7, MyFaces 1.2
    Spring 2.5.5
    Hibernate 3.x

    Thx in advance.

  • #2
    Your Dao is flawed. You are keeping state in a Singleton NEVER do this.

    Your getSession method should look like this.

    Code:
    protected Session getSession() {
      return sessionFactory.getCurrentSession();
    }
    Never assign the Session to an instance variable, you only have 1 instance!!! Now imagine 30 threads operating on that single instance?!

    Also make sure that your filter mapping is correct, which Servlet is processing your requests? If that isn't the 'Persistent Faces Servlet' then the filter isn't doing anything.

    Finally make sure that you have some sort of transactional configuration, I don't see a HibernateTransactionManager and neither any of the further transactional configuration.

    Comment


    • #3
      Thx for that advice so far, didnt see the forest full of trees ;-)
      Just copied the code from somewhere else and did not check for the session being held as attribute or retrieved every time from the SessionFactory.

      The Mapping is correct as 'Persistent Faces Servlet' is the name for the ICEfaces Servlet. I stripped the transaction config for better readability, in fact, Im using Springs declarative transaction management with annotations.

      One Problem remains and I'm sure it has something to do with transaction handling: All getter methods are working, but if I try to make an entity persistent, the corresponding method is not called and execution just stops without throwing an exception.

      This is my Businessmethod:
      Code:
          @Transactional(propagation=Propagation.REQUIRED)
          public void saveGP(Geschaeftspartner geschaeftspartner){
          	logger.debug("TEST");
          	geschaeftspartnerDAO.save(geschaeftspartner);
          	logger.debug("TEST2");
          }
      Here is the Corresponding DAO:
      Code:
      @Transactional
      public class GeschaeftspartnerDAOHibernate 
      	extends GenericHibernateDAO<Geschaeftspartner, Long> 
      	implements GeschaeftspartnerDAO{
      
      	Logger logger = Logger.getLogger(this.getClass());
      
      //  ... other methods 
      
      	public Geschaeftspartner save(Geschaeftspartner entity) {
      		logger.debug("save()");
      		return makePersistent(entity);
      	}
      	
      }
      finally the makePersistent() Method from the abstract GenericDAO superclass:
      Code:
      	@SuppressWarnings("unchecked")
      	public T makePersistent(T entity) {
      		logger.debug("Make Persistent!");
      		getSession().saveOrUpdate(entity);
      		logger.debug("Entity: "+entity);
      		return entity;
      	}
      When saveGP() is called, save() is invoked and the logging output "save()" created, but neither the logging-output from makePersistent(), nor the debug-output "TEST2" is written, so it seems like makePersistent() is not called.

      There is no @Transactional(readOnly=true) anywhere, so I have no Idea why persisting an item doesnt work...

      Comment


      • #4
        just found out that invoking getSession().saveOrUpdate() within the DAO implementation does the trick. But why isnt it working when a method with the same statement (and inherited from the abstract superclass GenericHibernateDAO) is called? Annotating the method with @Transactional
        changes nothing...

        Comment


        • #5
          The @Transactional should be on your service, also putting @Transactional on a method which is called internally isn't going to do anything (chapter 6 of the reference guide explains why).

          Also are they using the same logger instance and are the log levels set correctly?

          Comment


          • #6
            I changed the DAO's get SessionMethod now to

            Code:
            	protected Session getSession() {
            		Session newSession = sessionFactory.getCurrentSession();
            		logger.info("Session: "+newSession.hashCode());
            		return newSession;
            	}
            Lazy loading is still not possible, since there are 2 Different Sessions during one request. Looks like the SessionFactory misses to deliver the right session.

            I get a org.hibernate.LazyInitializationException everytime LazyLoading is used. Setting the attribute to lazy=true within the mapping solves the problem, but i want to uses the lazy mechanism here.

            Any idea?

            Comment


            • #7
              OK, i think I found something. Everything works fine if the filter-mapping is changed to

              Code:
              	
              <filter-mapping>
              		<filter-name>HibernateSessionFilter</filter-name>
              		<url-pattern>/*</url-pattern>
              	</filter-mapping>
              So it looks like the Persistent Mapping Servlet is not working as expected.

              Comment

              Working...
              X