Announcement Announcement Module
Collapse
No announcement yet.
Session closed Error with Spring + Hibernate + JPA Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Session closed Error with Spring + Hibernate + JPA

    Hello,

    I am trying to test the findAll methods and getting a "Session closed" error. Interestingly, all my previous calls in the junit class succeed. Why would the session be closed and I do I resolve this?

    Thanks

    Code:
    javax.persistence.PersistenceException: org.hibernate.SessionException: Session is closed!
    	at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:630)
    	at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:75)
    	at diamelle.common.service.ServiceDAOBean.findAll(ServiceDAOBean.java:96)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    	at java.lang.reflect.Method.invoke(Unknown Source)
    	at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:299)
    	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:196)
    	at $Proxy21.findAll(Unknown Source)
    	at diamelle.common.service.ServiceMgr.getAllServices(ServiceMgr.java:95)
    	at diamelle.common.service.ServiceMgr$$FastClassByCGLIB$$28b3d4a2.invoke(<generated>)
    	at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149)
    	at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621)
    	at diamelle.common.service.ServiceMgr$$EnhancerByCGLIB$$81b521e2.getAllServices(<generated>)
    	at test.diamelle.common.service.ServiceMgrTest.testGetAllServices(ServiceMgrTest.java:81)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    	at java.lang.reflect.Method.invoke(Unknown Source)
    	at junit.framework.TestCase.runTest(TestCase.java:164)
    	at junit.framework.TestCase.runBare(TestCase.java:130)
    	at org.springframework.test.ConditionalTestCase.runBare(ConditionalTestCase.java:69)
    	at junit.framework.TestResult$1.protect(TestResult.java:110)
    	at junit.framework.TestResult.runProtected(TestResult.java:128)
    	at junit.framework.TestResult.run(TestResult.java:113)
    	at junit.framework.TestCase.run(TestCase.java:120)
    	at junit.framework.TestSuite.runTest(TestSuite.java:228)
    	at junit.framework.TestSuite.run(TestSuite.java:223)
    	at org.junit.internal.runners.OldTestClassRunner.run(OldTestClassRunner.java:35)
    	at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38)
    	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
    	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
    	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
    	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
    Caused by: org.hibernate.SessionException: Session is closed!
    	at org.hibernate.impl.AbstractSessionImpl.errorIfClosed(AbstractSessionImpl.java:49)
    	at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1110)
    	at org.hibernate.impl.QueryImpl.list(QueryImpl.java:79)
    	at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:66)
    	... 34 more
    Service Manager Class:
    Code:
      public java.util.List<Service> getAllServices() {
    	  return serviceDao.findAll();
      }
    Service DAO class
    Code:
    	@SuppressWarnings("unchecked")
    	public List<Service> findAll() {
    		log.debug("getting all Service instances " );
    		try {
    			Query qry = entityManager.createNamedQuery("findAll");
    			return qry.getResultList();
    			
    			// return entityManager.createNamedQuery("findAll").getResultList(); 
    		} catch (RuntimeException re) {
    			log.error("get failed", re);
    			throw re;
    		}
    	}
    Service class:
    Code:
    @NamedQueries({
        @NamedQuery(
            name = "findChildServices",
            query = "select s from Service s where s.parentServiceId = :id"
        ),
        @NamedQuery(
         name = "findAll",
         query = "select s from Service s "
        ),
        @NamedQuery(
         name = "findByType",
         query = "select s from Service s where s.serviceType = :type"
        )
    
    })

  • #2
    Are you extending AbstractJpaTests? I can't see any transactions in the stacktrace, have you marked the test method with @Transactional?

    Comment


    • #3
      Hi Karl,

      I added the following annotation to my ServiceMgr class that is wrapping the dao and it now works. I put the tag on this class that I can call it from my web application and not have anything change between my test and the app. Is this the right way of doing this?

      @Transactional (propagation = Propagation.REQUIRED, readOnly = false)
      public java.util.List<Service> getAllServices() {
      return serviceDao.findAll();
      }


      I am a little confused though. In my findById object, I did not have to add a @Transaction annotation, so why do I need it here?

      In my test class I am not extending the AbstractJpaTests, but I will.

      Thanks again for your help

      Comment


      • #4
        Glad you've got something working. If you want to use @Transactional that's the right way to do it. There are other ways of providing the transaction though, the reference manual is your best bet here. You don't need to put the transaction on the findAll method as it's participating in the transaction provided by the service. AbstractJpaTests is a good idea as well, the Spring test classes make things much easier.

        Comment


        • #5
          In your spring config file - give <tx:annotation-driven/>. This should solve the problem

          Comment


          • #6
            I have the same problem but i tried all your suggesions above without success.
            ----> applicationContext.xml
            <?xml version="1.0" encoding="UTF-8"?>
            <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:mvc="http://www.springframework.org/schema/mvc"
            xmlns:context="http://www.springframework.org/schema/context"
            xmlns:cache="http://www.springframework.org/schema/cache"
            xmlns="http://www.springframework.org/schema/p"
            xmlns:tx="http://www.springframework.org/schema/tx"
            xmlns="http://www.springframework.org/schema/beans"
            xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schem...-beans-3.0.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schem...ng-mvc-3.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schem...ontext-3.0.xsd
            http://www.springframework.org/schema/cache http://www.springframework.org/schem...ring-cache.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
            " >

            <!-- bean
            id="localLogAdministrator"
            class="com.atomikos.icatch.admin.imp.LocalLogAdmin istrator" /-->

            <bean
            id="userTransactionService"
            class="com.atomikos.icatch.config.UserTransactionS erviceImp"
            destroy-method="shutdownForce"
            init-method="init" >

            <constructor-arg>

            <!-- IMPORTANT: specify all Atomikos properties here -->

            <props>

            <prop key="com.atomikos.icatch.service" >
            com.atomikos.icatch.standalone.UserTransactionServ iceFactory
            </prop>
            </props>
            </constructor-arg>

            <!-- property name="initialLogAdministrators" >

            <list>

            <ref bean="localLogAdministrator" />
            </list>
            </property-->
            </bean>

            <!--
            Construct Atomikos UserTransactionManager,
            needed to configure Spring
            -->

            <bean
            id="atomikosTransactionManager"
            class="com.atomikos.icatch.jta.UserTransactionMana ger"
            depends-on="userTransactionService"
            destroy-method="close"
            init-method="init" >

            <!-- IMPORTANT: disable startup because the userTransactionService above does this -->

            <property
            name="startupTransactionService"
            value="false" />

            <!--
            when close is called,
            should we force transactions to terminate or not?
            -->

            <property
            name="forceShutdown"
            value="false" />
            </bean>

            <!--
            Also use Atomikos UserTransactionImp,
            needed to configure Spring
            -->

            <bean
            id="atomikosUserTransaction"
            class="com.atomikos.icatch.jta.UserTransactionImp"
            depends-on="userTransactionService" >
            <property
            name="transactionTimeout"
            value="300" />
            </bean>

            <!-- Configure the Spring framework to use JTA transactions from Atomikos -->

            <bean
            id="jtaTransactionManager"
            class="org.springframework.transaction.jta.JtaTran sactionManager"
            depends-on="userTransactionService" >

            <property
            name="transactionManager"
            ref="atomikosTransactionManager" />
            <property name="allowCustomIsolationLevels" value="true" />
            <property
            name="userTransaction"
            ref="atomikosUserTransaction" />
            </bean>

            <!-- JBoss -->
            <!--
            bean id="transactionManager" class="org.springframework.transaction.jta.JtaTran sactionManager">
            <property name="transactionManagerName">
            <value>java:/TransactionManager</value>
            </property>
            </bean
            -->

            <bean
            id="applicationContextListener"
            class="it.opera21.support.ApplicationContextListen er" />

            <cache:annotation-driven />

            <bean
            id="cacheManager"
            class="org.springframework.cache.ehcache.EhCacheCa cheManager"
            p:cache-manager-ref="ehcache" />

            <bean
            id="ehcache"
            class="org.springframework.cache.ehcache.EhCacheMa nagerFactoryBean"
            p:config-location="classpath:ehcache.xml" />



            <context:annotation-config />
            <!-- context:component-scan base-package="it.opera21.event" /-->
            <!-- context:component-scan base-package="it.opera21.batch" /-->

            <context:component-scan base-package="it.opera21.dao" />

            <context:component-scan base-package="it.opera21.service" />

            <import resource="/dao/context.xml" />

            <import resource="/service/context.xml" />

            <import resource="/extra/context.xml" />

            <tx:annotation-driven transaction-manager="jtaTransactionManager" />
            <!-- import resource="/security/context.xml" / -->

            </beans>

            /dao/context.xml

            Comment


            • #7
              <?xml version="1.0" encoding="UTF-8"?>
              <beans xmlns="http://www.springframework.org/schema/beans"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xmlns="http://www.springframework.org/schema/p"
              xmlns:tx="http://www.springframework.org/schema/tx"
              xmlns:context="http://www.springframework.org/schema/context"
              xsi:schemaLocation="http://www.springframework.org/schema/beans
              http://www.springframework.org/schem...ring-beans.xsd
              http://www.springframework.org/schema/tx
              http://www.springframework.org/schema/tx/spring-tx.xsd
              http://www.springframework.org/schema/context http://www.springframework.org/schem...ontext-3.0.xsd
              ">



              <bean
              class="org.springframework.beans.factory.config.Pr opertyPlaceholderConfigurer">
              <property name="locations">
              <value>classpath:jdbc.properties</value>
              </property>
              </bean>

              <!-- enables interpretation of the @Required annotation to ensure that dependency
              injection actually occures -->
              <!-- utilroperties id="jdbcConfiguration" location="classpath:jdbcdatasource.properties"/-->

              <!-- configure an Atomikos JTA-aware datasource -->
              <!-- bean id="support_datasource"
              class="com.atomikos.jdbc.AtomikosDataSourceBean"
              init-method="init" destroy-method="close"-->
              <!-- set an arbitrary but unique name for the datasource -->
              <!-- property name="uniqueResourceName" value="XADBMS" /-->
              <!--property name="maxPoolSize" value="50"/-->
              <!--property name="minPoolSize" value="5"/-->
              <!--
              set the underlying driver class to use,
              in this example case we use Oracle
              -->
              <!-- property name="xaDataSourceClassName" value="${datasource.classname}"/-->
              <!--property name="xaProperties" ref="jdbcConfiguration" /-->

              <!-- how many connections in the pool? -->
              <!-- property name="poolSize" value="3"/-->
              <!--/bean-->



              <bean id="support_datasource"
              class="org.springframework.jdbc.datasource.DriverM anagerDataSource">
              <property name="driverClassName">
              <value>${jdbc.driverClassName}</value>
              </property>
              <property name="url">
              <value>${jdbc.url}</value>
              </property>
              <property name="username">
              <value>${jdbc.username}</value>
              </property>
              <property name="password">
              <value>${jdbc.password}</value>
              </property>
              <property name="connectionProperties">
              <props>
              <prop key="AutoCommit">false</prop>
              </props>
              </property>

              </bean>
              <bean id="dwh_datasource"
              class="org.springframework.jdbc.datasource.DriverM anagerDataSource">
              <property name="driverClassName">
              <value>${jdbc.driverClassName.app}</value>
              </property>
              <property name="url">
              <value>${jdbc.url.app}</value>
              </property>
              <property name="username">
              <value>${jdbc.username.app}</value>
              </property>
              <property name="password">
              <value>${jdbc.password.app}</value>
              </property>

              </bean>


              <!-- bean id="pum" class="org.springframework.orm.jpa.persistenceunit .DefaultPersistenceUnitManager">

              <property name="persistenceXmlLocations" >
              <list value-type="java.lang.String" >
              <value >classpathersistence.xml</value>

              </list>
              </property>
              <property name="dataSources">
              <map>
              <entry key="support_datasource" value-ref="support_datasource"/>
              <entry key="dwh_datasource" value-ref="dwh_datasource"/>
              </map>
              </property>

              <property name="defaultDataSource" ref="support_datasource"/>
              </bean-->

              <bean id="entityManagerFactory_support"
              class="org.springframework.orm.jpa.LocalContainerE ntityManagerFactoryBean">
              <property name="persistenceXmlLocation" value="classpath:support_persistence.xml"/>
              <property name="dataSource" ref="support_datasource"/>
              <property name="persistenceUnitName" value="ianus_support"/>

              <!-- property name="loadTimeWeaver" ref="loadTimeWeaver" / -->
              <property name="jpaVendorAdapter">
              <bean class="org.springframework.orm.jpa.vendor.Hibernat eJpaVendorAdapter">
              <property name="showSql" value="true" />
              <property name="generateDdl" value="true" />
              </bean>
              </property>

              <property name="jpaProperties">

              <props>
              <prop key="javax.persistence.transactionType" >JTA</prop>
              <!-- prop key="hibernate.current_session_context_class">jta</prop-->
              <prop key="hibernate.transaction.flush_before_completion ">true</prop>
              <prop key="hibernate.transaction.auto_close_session" >true</prop>

              <prop key="hibernate.connection.release_mode" >auto</prop>
              <prop key="hibernate.id.new_generator_mappings">false</prop>
              <prop key="hibernate.transaction.jta.platform">
              com.atomikos.icatch.jta.hibernate4.AtomikosJtaPlat form
              </prop>

              <prop key="hibernate.dialect">${jdbc.dialect}</prop>
              <!-- >prop key="hibernate.cache.use_second_level_cache">true</prop>
              <prop key="hibernate.cache.use_query_cache">true</prop-->
              <prop key="atomikos.transaction.timeout">3000</prop>
              <prop key="hibernate.cache.region.factory_class">org.hib ernate.cache.ehcache.EhCacheRegionFactory</prop>
              <prop key="hibernate.generate_statistics">true</prop>
              </props>
              </property>

              </bean>

              <bean id="entityManagerFactory_dwh"
              class="org.springframework.orm.jpa.LocalContainerE ntityManagerFactoryBean" depends-on="jtaTransactionManager">
              <property name="persistenceXmlLocation" value="classpath:dwh_persistence.xml"/>
              <property name="dataSource" ref="dwh_datasource"/>
              <property name="persistenceUnitName" value="ianus_dwh"/>

              <!-- property name="loadTimeWeaver" ref="loadTimeWeaver" / -->
              <property name="jpaVendorAdapter">
              <bean class="org.springframework.orm.jpa.vendor.Hibernat eJpaVendorAdapter">
              <property name="showSql" value="true" />
              <property name="generateDdl" value="true" />
              </bean>
              </property>

              <property name="jpaProperties">

              <props>

              <prop key="javax.persistence.transactionType" >JTA</prop>
              <!-- prop key="hibernate.current_session_context_class">jta</prop-->
              <prop key="hibernate.transaction.flush_before_completion ">true</prop>
              <prop key="hibernate.transaction.auto_close_session" >true</prop>

              <prop key="hibernate.connection.release_mode" >auto</prop>
              <prop key="hibernate.id.new_generator_mappings">false</prop>
              <prop key="hibernate.transaction.jta.platform">
              com.atomikos.icatch.jta.hibernate4.AtomikosJtaPlat form
              </prop>

              <prop key="hibernate.dialect">${jdbc.dialect.app}</prop>
              <!-- >prop key="hibernate.cache.use_second_level_cache">true</prop>
              <prop key="hibernate.cache.use_query_cache">true</prop-->
              <prop key="atomikos.transaction.timeout">3000</prop>
              <prop key="hibernate.cache.region.factory_class">org.hib ernate.cache.ehcache.EhCacheRegionFactory</prop>
              <prop key="hibernate.generate_statistics">true</prop>
              </props>
              </property>

              </bean>


              <bean class="org.springframework.dao.annotation.Persiste nceExceptionTranslationPostProcessor"/>
              <bean
              class="org.springframework.beans.factory.annotatio n.RequiredAnnotationBeanPostProcessor" />

              <bean class="org.springframework.orm.jpa.support.Persist enceAnnotationBeanPostProcessor" />



              <bean id="defaultLobHandler" class="org.springframework.jdbc.support.lob.Defaul tLobHandler"
              lazy-init="false" />

              <tx:annotation-driven transaction-manager="jtaTransactionManager" />

              </beans>

              Comment

              Working...
              X