Getting "Session is closed" exception sometimes - spring

I am using Spring + JPA + Hibernate in my project.
The project is structured as below:
- DAO layer - responsible to get data. DAO returns data in form of Model objects.
- Service layer - Calls DAO and processes/transforms the (Model) data in form required by UI.
I am using #Transactional for methods on Service layer.
I am facing problem where sometimes I get "Session is closed" error while reading data from a Lazily loaded collection.
Also I am not facing this problem consistently.
I get this error sometimes while running from TestNG tests and also when the application is deployed as WAR.
I am pasting the exception I get while running the TestNG tests:
org.hibernate.SessionException: Session is closed!
at org.hibernate.impl.AbstractSessionImpl.errorIfClosed(AbstractSessionImpl.java:72)
at org.hibernate.impl.SessionImpl.getBatcher(SessionImpl.java:305)
at org.hibernate.loader.Loader.doQuery(Loader.java:854)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
at org.hibernate.loader.Loader.loadEntity(Loader.java:2037)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:86)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:76)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3268)
at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:496)
at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:477)
at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:227)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:147)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:1090)
at org.hibernate.impl.SessionImpl.immediateLoad(SessionImpl.java:1026)
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:176)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:215)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
at com.applications.qi.etplugin.et.model.impl.ETTestCasePackage_$$_javassist_21.getVertical(ETTestCasePackage_$$_javassist_21.java)
at com.applications.qi.etplugin.et.model.impl.ETTestCasePackage.getVertical(ETTestCasePackage.java:78)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:197)
at com.applications.qi.etplugin.et.model.impl.ETTestCasePackage_$$_javassist_21.getVertical(ETTestCasePackage_$$_javassist_21.java)
at com.applications.qi.etplugin.et.dao.impl.TestCaseDAOTest.Test2(TestCaseDAOTest.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
at org.testng.internal.MethodInvocationHelper$1.runTestMethod(MethodInvocationHelper.java:182)
at org.springframework.test.context.testng.AbstractTestNGSpringContextTests.run(AbstractTestNGSpringContextTests.java:158)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.testng.internal.MethodInvocationHelper.invokeHookable(MethodInvocationHelper.java:194)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:695)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:894)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1219)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
This is my first project using Spring / JPA / Hibernate.
I am not able to find out what may be causing this problem?
Also what can be done to resolve this problem?
Please let me if some more information is required.
Any help / pointers are highly appreciated :)

When you are fetching Lazy objects you receives proxy objects instead of real one.
This is probably happened because you are trying to access not initiated Proxy object after your Transaction finished and session closed.
I believe you need to consider on of two options:
Seriously review your Transaction boundaries, and make sure that all your object operation happens inside those transaction boundaries. It will be something like "Open Session In View" design pattern.
Make all your collections EAGER. In that case you will receive a lot of unnecessary database queries.
Hope it helps.

Related

java.lang.IllegalStateException: Unable to detect database type for Sybase datasource

I am getting the Unable to detect database type for Sybase Datasource configured in my spring boot application.
Spring boot version: 1.5.3
application.properties
spring.datasource.url=jdbc:jtds:sybase://db-server-name:5555/DBNAME
spring.datasource.username=db_user
spring.datasource.password=db_password
spring.datasource.driver-class-name=net.sourceforge.jtds.jdbc.Driver
spring.jpa.database=sybase
spring.jpa.database-platform=org.hibernate.dialect.SybaseDialect
Debug Information:
// line number 75 in AbstractDatabaseInitializer class
String productName = JdbcUtils.commonDatabaseName(JdbcUtils
.extractDatabaseMetaData(this.dataSource, "getDatabaseProductName")
.toString());
// productName is returned as Sybase from JdbcUtils.extractDatabaseMetaData
DatabaseDriver databaseDriver = DatabaseDriver.fromProductName(productName);
// but there is no databaseDriver found and is returned as UNKNOWN.
// There is no Sybase database configured in DatabaseDriver enum
There is no Sybase datasource configured in DatabaseDriver enum. Can you quickly help to fix this issue ?
Error Stack Trace for reference:
Caused by: java.lang.IllegalStateException: Unable to detect database type
at org.springframework.boot.autoconfigure.AbstractDatabaseInitializer.getDatabaseName(AbstractDatabaseInitializer.java:80)
at org.springframework.boot.autoconfigure.batch.BatchDatabaseInitializer.getDatabaseName(BatchDatabaseInitializer.java:54)
at org.springframework.boot.autoconfigure.AbstractDatabaseInitializer.initialize(AbstractDatabaseInitializer.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:311)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:134)
... 17 common frames omitted
It works for me. Just put this property in application.properties file. I was facing issue with mysql so I passed mysql here if you are using some other database just pass that(for example: schema-sybase.sql)
spring.batch.schema=classpath:org/springframework/batch/core/schema-mysql.sql
It looks like our detection algorithm is broken with MySQL so I've created this issue to double check it.
In the meantime, please specify the path to your initalization script, this will prevent Spring Boot to attempt to auto-detect it.

Connection is not associated with a managed connection , "Spring application in Jboss Server"

Below Exception is coming in specific server, issue is not consistent.
org.springframework.jdbc.support.MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is java.sql.SQLException:
Connection is not associated with a managed connection.org.jboss.resource.adapter.jdbc.jdk6.WrappedConnectionJDK6#49828f4c
at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:296)
at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:320)
at org.springframework.jdbc.support.SQLErrorCodesFactory.getErrorCodes(SQLErrorCodesFactory.java:213)
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.setDataSource(SQLErrorCodeSQLExceptionTranslator.java:141)
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.<init>(SQLErrorCodeSQLExceptionTranslator.java:104)
at org.springframework.jdbc.support.JdbcAccessor.getExceptionTranslator(JdbcAccessor.java:99)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:969)
at org.springframework.jdbc.core.JdbcTemplate.call(JdbcTemplate.java:1003)
at org.springframework.jdbc.object.StoredProcedure.execute(StoredProcedure.java:144)
at com.watsons.tfo.sp.dao.SPSaveTransactionDetail.execute(SupplierPromotionDaoImpl.java:3354)
at com.watsons.tfo.sp.dao.SupplierPromotionDaoImpl.savePromoTransaction(SupplierPromotionDaoImpl.java:422)
at com.watsons.tfo.sp.service.SupplierPromotionServiceImpl.savePromoTransaction(SupplierPromotionServiceImpl.java:158)
at sun.reflect.GeneratedMethodAccessor1010.invoke(Unknown Source)
--
org.springframework.dao.RecoverableDataAccessException: CallableStatementCallback; SQL [{call PKG_TFO_SUPPLIER_PROMOTION.PR_INS_SAVE_TRANSACTION_DET(?, ?)}]; No more data to read from socket; nested exception is java.sql.SQLRecoverableException: No more data to read from socket
at com.watsons.tfo.sp.service.SupplierPromotionServiceImpl.savePromoTransaction(SupplierPromotionServiceImpl.java:160)
at sun.reflect.GeneratedMethodAccessor1010.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy206.savePromoTransaction(Unknown Source)
at com.watsons.tfo.sp.controller.SupplierPromoTransactionController.saveSupplierPromoTransaction(SupplierPromoTransactionController.java:1077)
at com.watsons.tfo.sp.controller.SupplierPromoTransactionController$$FastClassByCGLIB$$8994f9f9.invoke(<generated>)
First i thought the is because of stale connection, So I have added stale connection checker in the oracle-ds.xml. But again the issue is came up
Please help me to resolve this.
Disabling the CachedConnection Manager
<Valve className="org.jboss.web.tomcat.tc5.jca.CachedConnectionValve"
cachedConnectionManagerObjectName="jboss.jca:service=CachedConnectionManager"
transactionManagerObjectName="jboss:service=TransactionManager" />
The above tag is mentioned in server.xml. this cachedconnectionvalve should be turned off in production server.
There are two main configuration parameters that have a direct effect on performance and scalability: cached connection manager and HTTP session replication.
The CachedConnectionManager is configured to be in the servlet container in debug mode. It's also configured in the production configuration but with debug mode off.
I commented the CachedConnectionValve at end of the server.xml file.
Also commented the CachedConnectionManager in META-INF/jboss-service.xml.
The "Connection is not associated with a managed connection" is gone and application is running fine.
Update:
Found one more log for the same error in the oracle log files...
Oracle version: Oracle Database 11.2.0.2
i.e XMLSEQUENC/EEXTRACT FAILS WITH ORA-7445[__INTEL_NEW_MEMCPY()+5395]
This is the bug with the XML Processing in oracle DB version, Then
After instructed by oracle people, Updated the patch (11666959) for oracle .
Same is mentioned in oracle web site.
11666959 is required for the release utility; XMLSEQUENC/EEXTRACT FAILS WITH ORA-7445[__INTEL_NEW_MEMCPY()+5395] IN 11.2.0.2

Spring Data Neo4j - Cross store persistence

I am new to SDN, I am trying to do a cross store persistence with hibernate. The tutorial given in website has examples for the same, I have checked the github ones too. I have two questions
I am unable to do xml configuration as mentioned in the docs or examples. <neo4j:config/> doesn't support entityManagerFactory. My assumption is it creates the default Neo4jConfiguration which doesn't have a setter for entityManagerFactory. The workaround i have found is to define a CrossStoreNeo4jConfiguration bean.
#Bean
public CrossStoreNeo4jConfiguration crossStoreNeo4jConfiguration(){
CrossStoreNeo4jConfiguration configuration = new CrossStoreNeo4jConfiguration();
configuration.setEntityManagerFactory(entityManagerFactory);
configuration.setGraphDatabaseService(graphDatabaseService);
return configuration;
}
How to do this inside<neo4j:config/>
What happens when you refer a Neo4jTemplate to your repository using neo4j-template-ref when you define repositories using neo4j:repositories? what is the purpose?
UDPATE
The reason it was unable to create CrossStoreNeo4jConfiguration with <neo4j:config/> was , i was missing the dependency spring-data-neo4j-cross-store`. But now i get exception on application start up.
Caused by: java.lang.IllegalStateException: Singleton 'nodeEntityStateFactory' isn't currently in creation
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.afterSingletonCreation(DefaultSingletonBeanRegistry.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:239)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:292)
at org.springframework.data.neo4j.cross_store.config.CrossStoreNeo4jConfiguration$$EnhancerByCGLIB$$779c5955.nodeEntityStateFactory(<generated>)
at org.springframework.data.neo4j.config.Neo4jConfiguration.mappingContext(Neo4jConfiguration.java:199)
at org.springframework.data.neo4j.cross_store.config.CrossStoreNeo4jConfiguration$$EnhancerByCGLIB$$779c5955.CGLIB$mappingContext$11(<generated>)
at org.springframework.data.neo4j.cross_store.config.CrossStoreNeo4jConfiguration$$EnhancerByCGLIB$$779c5955$$FastClassByCGLIB$$3134c8a8.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:280)
at org.springframework.data.neo4j.cross_store.config.CrossStoreNeo4jConfiguration$$EnhancerByCGLIB$$779c5955.mappingContext(<generated>)
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.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:149)
Thanks in advance.
This should work:
<neo4j:config entityManagerFactory="entityManagerFactory"/>
No need to create your custom implementation.
The template passed to the repository config is the one used by its infrastructure. In most cases there is no need to configure something different.

Spring 3 application instantiating a class provided by Tomcat

I have a Spring 3 application that is loading a library. The library consists of JAX-WS generated Java bindings. When the library is included in the WAR file and deployed to Tomcat the application runs great.
However when we moved the library into Tomcat (CATALINA_HOME/lib) Spring is no long able to instantiate classes in the library due to what looks like a classloader issue:
Caused by: java.lang.IllegalArgumentException: interface com.sun.xml.ws.developer.WSBindingProvider is not visible from class loader
at java.lang.reflect.Proxy.getProxyClass(Proxy.java:353) ~[na:1.6.0_24]
at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:581) ~[na:1.6.0_24]
at com.sun.xml.ws.client.WSServiceDelegate.createEndpointIFBaseProxy(WSServiceDelegate.java:604) ~[jaxws-rt-2.2.1.jar:2.2.1]
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:344) ~[jaxws-rt-2.2.1.jar:2.2.1]
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:326) ~[jaxws-rt-2.2.1.jar:2.2.1]
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:308) ~[jaxws-rt-2.2.1.jar:2.2.1]
at javax.xml.ws.Service.getPort(Service.java:92) ~[na:1.6.0_24]
at org.ghc.webservices.element.services.stubs.Express.getExpressSoap12(Express.java:94) ~[element-soap-libs-dev-1.16.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.6.0_24]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.6.0_24]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.6.0_24]
at java.lang.reflect.Method.invoke(Method.java:597) ~[na:1.6.0_24]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:145) ~[spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE]
Unfortunately we need to keep this library external to the application.
I am stumped on how to correct this issue and would appreciate any suggestions.
-Thanks!
are you sure the directory that you placed the library in, is available in the classpath? we normally place our external libraries in common\lib like this.
%CATALINA_HOME%\common\lib\<yourjar>.jar
And if that didn't work then try explicitly appending the your jar and set in classpath in catalina.bat file.
set CLASSPATH=%CLASSPATH%;%CATALINA_HOME%\common\lib\<yourjar>.jar

java.lang.IllegalStateException: Cannot deserialize BeanFactory with id org.springframework.web.context.WebApplicationContext

When I stop my server I get this exception:
SEVERE: Exception loading sessions from persistent storage
java.lang.IllegalStateException: Cannot deserialize BeanFactory with id org.springframework.web.context.WebApplicationContext:/Life: no factory registered for this id
at org.springframework.beans.factory.support.DefaultListableBeanFactory$SerializedBeanFactoryReference.readResolve(DefaultListableBeanFactory.java:953)
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 java.io.ObjectStreamClass.invokeReadResolve(Unknown Source)
Why is that?
My guess: when spring beans are serialized (for example, as part of the http session), on restoring spring tries not to restore their original values (since they might be meaningless after the deserialization), but instead tries to fetch them by their id. If you have changed your bean definitions and have removed the bean in question, and spring tries to deserialize it (from where it has serialized it, under circumstances which I don't know based on the information given), it would throw the exception that no such bean exists.

Resources