Hibernate CreateNativeQuery does not close the connection when the exception arises - java

I face one issue related to the hibernate CreateNativeQuery.
I have executed the query using the createNativeQuery and return the resultList. If the execution of query fails due to the incorrect query or the reasons, the exception is raised and the connection which is used by the entity manager is not closed. Why the connection is not closed message arrived?
If I use the createQuery method I had faced only the exception and connection is closed properly by the entity manager.
What's the reason behind this???
My code is
return em.createNativeQuery(queryToExecute).getResultList();
Why is the connection not closed if I use the createNativeQuery method?
Log Details
2015-03-13 11:21:40,504 WARN [org.jboss.jca.adapters.jdbc.WrappedConnection] Closing a statement you left open, please do your own housekeeping: java.lang.Throwable: STACKTRACE
at org.jboss.jca.adapters.jdbc.WrappedConnection.registerStatement(WrappedConnection.java:1672) at org.jboss.jca.adapters.jdbc.WrappedStatement.<init>(WrappedStatement.java:105)
at org.jboss.jca.adapters.jdbc.WrappedPreparedStatement.<init>(WrappedPreparedStatement.java:69)
at org.jboss.jca.adapters.jdbc.jdk6.WrappedPreparedStatementJDK6.<init>(WrappedPreparedStatementJDK6.java:52)
at org.jboss.jca.adapters.jdbc.jdk6.WrappedConnectionJDK6.wrapPreparedStatement(WrappedConnectionJDK6.java:79)
at org.jboss.jca.adapters.jdbc.WrappedConnection.prepareStatement(WrappedConnection.java:404)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:161)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:182)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:159)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1854)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1831)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1811)
at org.hibernate.loader.Loader.doQuery(Loader.java:899)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:341)
at org.hibernate.loader.Loader.doList(Loader.java:2516)
at org.hibernate.loader.Loader.doList(Loader.java:2502)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2332)
at org.hibernate.loader.Loader.list(Loader.java:2327)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:338)
at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1826)
at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:231)
at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:157)
at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:264)
2015-03-13 11:21:40,506 INFO [org.jboss.jca.core.api.connectionmanager.ccm.CachedConnectionManager] IJ000100: Closing a connection for you. Please close them yourself: org.jboss.jca.adapters.jdbc.jdk6.WrappedConnectionJDK6#7bc7c07d: java.lang.Throwable: STACKTRACE
at org.jboss.jca.core.connectionmanager.ccm.CachedConnectionManagerImpl.registerConnection(CachedConnectionManagerImpl.java:269)
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.allocateConnection(AbstractConnectionManager.java:495)
at org.jboss.jca.adapters.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:139)
at org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider.getConnection(InjectedDataSourceConnectionProvider.java:70)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:292)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:214)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:157)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.connection(StatementPreparerImpl.java:56)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:161)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:182)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:159)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1854)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1831)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1811)
Thanks in advance.

Related

How to resolve unable to obtain isolated JDBC connection?

I changed hibernate timeout settings as well as idle time but it not working
My hibernate properties are
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300000</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">300000</property>
And, I'm getting following exception :
Exception in thread "main" org.hibernate.exception.JDBCConnectionException: unable to obtain isolated JDBC connection
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:115)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:103)
at org.hibernate.id.enhanced.TableGenerator$1.getNextValue(TableGenerator.java:530)
at org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)
at org.hibernate.id.enhanced.TableGenerator.generate(TableGenerator.java:526)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:105)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:682)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
at com.ihealthmantra.upload.com.ihealthmantra.customer.upload.service.SellerUploadImpl.lambda$4(SellerUploadImpl.java:801)
at java.util.ArrayList.forEach(Unknown Source)
at com.ihealthmantra.upload.com.ihealthmantra.customer.upload.service.SellerUploadImpl.createTimeSlotUploadedSeller(SellerUploadImpl.java:738)
at com.ihealthmantra.upload.com.ihealthmantra.customer.upload.service.SellerUploadImpl.populateSlot(SellerUploadImpl.java:1146)
at com.ihealthmantra.upload.App.main(App.java:81)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 820,677 milliseconds ago. The last packet sent successfully to the server was 820,679 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:990)
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3746)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2509)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2480)
at com.mysql.jdbc.ConnectionImpl.setAutoCommit(ConnectionImpl.java:4811)
at com.mchange.v2.c3p0.impl.NewProxyConnection.setAutoCommit(NewProxyConnection.java:912)
at org.hibernate.c3p0.internal.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:78)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:386)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:48)
... 17 more
Caused by: java.net.SocketException: Connection reset by peer: socket write error
It was working fine earlier, but as data grown recently, it started throwing above exception.
... the server was 820,679 milliseconds ago. is longer than the server
configured value of 'wait_timeout'...
It seems like connection to database server is taking longer time than the value set for timeout. And it was mentioned in your exception as well.
To resolved this issue, either you can increase timeout value or pass autoReconnect=true with your JDBC string (as mentioned in your exception)
To change wait_timeout value in MySQL, you could refer existing post.
MySQL wait_timeout Variable - GLOBAL vs SESSION
OR
Append autoReconnect=true to your JDBC url string
jdbc:mysql://localhost:3306/exodb?autoReconnect=true

Find real error cause when acquiring connection with c3po ComboPooledDataSource

I am trying to get connection from ComboPooledDataSource, but let's say I made a typo in the password. I would like to get the information about the actual error cause, but all I can from the thrown exception is that something went wrong. Is there a way to find out what the real problem is, in form of a String that can be displayed to the user?
I am using c3po-0.9.1.2.
Let's be concrete, my code looks like this:
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass("org.postgresql.Driver");
ds.setJdbcUrl("jdbc:postgresql://localhost:5432/my_db");
ds.setUser("user1");
ds.setPassword("wrong-password");
try {
Connection c = ds.getConnection();
...
} catch (Exception e) {
e.printStackTrace();
}
The ds.getConnection() code throws an exception, which prints the following stakctrace:
java.sql.SQLException: Connections could not be acquired from the underlying database!
at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:106)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:529)
at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:128)
at test.ConnectionErrorDemo.main(ConnectionErrorDemo.java:21)
Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1319)
at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:557)
at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:477)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:525)
... 2 more
So, this exception is not helpful at all, as it does not say anything about the actual cause of the problem. However, in the console you can also see log entries like this, which describe the actual problem:
WARNING: com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask#249939c3 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception:
org.postgresql.util.PSQLException: FATAL: password authentication failed for user "user1"
at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:398)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:173)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:64)
at org.postgresql.jdbc2.AbstractJdbc2Connection.<init>(AbstractJdbc2Connection.java:136)
at org.postgresql.jdbc3.AbstractJdbc3Connection.<init>(AbstractJdbc3Connection.java:29)
at org.postgresql.jdbc3g.AbstractJdbc3gConnection.<init>(AbstractJdbc3gConnection.java:21)
at org.postgresql.jdbc4.AbstractJdbc4Connection.<init>(AbstractJdbc4Connection.java:31)
at org.postgresql.jdbc4.Jdbc4Connection.<init>(Jdbc4Connection.java:24)
at org.postgresql.Driver.makeConnection(Driver.java:393)
at org.postgresql.Driver.connect(Driver.java:267)
at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:134)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014)
at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32)
at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810)
at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547)
If I understand that correctly, this log entry is done by the c3po library itself, an therefore I thought maybe there is a way to access this information somehow. Any ideas?

Stack trace of javax.transaction.RollbackException missing the cause

I have a stack trace with a javax.transaction.RollbackException:
[...] Caused by:
ch.ethz.id.wai.lakshmi.engine.common.LakshmiException: Error
processing user transaction. at
ch.ethz.id.wai.lakshmi.engine.common.TransactionHelper.commitTransaction(TransactionHelper.java:79)
at
ch.ethz.id.wai.lakshmi.stdcmp.persistency.StandardPersistency.registerOrder(StandardPersistency.java:110)
Caused by: javax.transaction.RollbackException: Transaction marked for
rollback. at
com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:473)
at
com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:855)
at
com.sun.enterprise.transaction.UserTransactionImpl.commit(UserTransactionImpl.java:208)
at
ch.ethz.id.wai.lakshmi.engine.common.TransactionHelper.commitTransaction(TransactionHelper.java:74)
at
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1387)
at
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1310)
at
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1316)
at
org.hibernate.ejb.AbstractEntityManagerImpl$CallbackExceptionMapperImpl.mapManagedFlushFailure(AbstractEntityManagerImpl.java:1510)
at
org.hibernate.engine.transaction.synchronization.internal.SynchronizationCallbackCoordinatorImpl.beforeCompletion(SynchronizationCallbackCoordinatorImpl.java:109)
at
org.hibernate.engine.transaction.synchronization.internal.RegisteredSynchronization.beforeCompletion(RegisteredSynchronization.java:53)
at
com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:435)
at
org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at
org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at
org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at com.sun.proxy.$Proxy233.executeUpdate(Unknown Source) at
org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:56)
at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3028)
at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3469)
at
org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:88)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:362)
at
org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:354)
at
org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:275)
at
org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:326)
at
org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1213) at
org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:402)
at
org.hibernate.engine.transaction.synchronization.internal.SynchronizationCallbackCoordinatorImpl.beforeCompletion(SynchronizationCallbackCoordinatorImpl.java:104)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:439) at
oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:395) at
oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:802) at
oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:436) at
oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:186) at
oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:521) at
oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:205)
at
oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1008)
at
oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1307)
at
oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3449)
at
oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3530)
at
oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1350)
at
com.sun.gjc.spi.base.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.java:125)
at
org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
The RollbackException has a cause that I can see while debugging:
javax.persistence.PersistenceException:
org.hibernate.exception.GenericJDBCException: ORA-22295: cannot bind
more than 4000 bytes data to LOB and LONG columns in 1 statement
which is in turn caused by
org.hibernate.exception.GenericJDBCException: ORA-22295: cannot bind
more than 4000 bytes data to LOB and LONG columns in 1 statement
But the cause of the RollbackExeption is not shown in the stack trace (which would ease the debugging of the errors).
Any idea of the reason?
Edit
I added a try-catch in the test method (JUnit):
#Test
public void foo() throws Throwable {
try {
// test code generating the exception
} catch ( Exception e ) {
// here the exception cause is still there
}
Since this method is called directly by JUnit the exception is still OK when it leaves my code.
If you like to have the cause shown in the exception, I guess your only chance is to open a bug/improvement request at Glassfish. I looked at the source code of JavaEETransactionImpl, which is where the RollbackException is thrown and at line 473 the code is:
rbe = new RollbackException(sm.getString("enterprise_distributedtx.mark_rollback"));
As you can see, I am checking version 3.1.1, so in case you have a different version please take a look to the right source code (which I doubt will differ anyway).
The problem was Ant erroneously filtering part of the exception trace
From the Junit task documentation:
filtertrace Filter out Junit and Ant stack frames from error and failure stack traces.
It defaults to on but it does not only filter Junit and Ant frames: setting it to off the cause of the rollback is shown.

I am getting Cannot get a connection, pool error Timeout waiting for idle object, When I try to create more than 250 threads in my web application [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Connection Pool Exception: Cannot get a connection, pool error Timeout waiting for idle object
I am getting Cannot get a connection, pool error Timeout waiting for idle object error, When I try to create more than 250 threads in my web application. I am creating web application using JSF 2.0 and Hibernate.
I have tried with modified hibernate.xml,server.xml,context.xml and also mysql properties.
The followings are I am getting.
WARN (JDBCExceptionReporter.java:233) - SQL Error: 0, SQLState: null
ERROR (JDBCExceptionReporter.java:234) - Cannot get a connection, pool error Timeout waiting for idle object
ERROR (BaseServlet.java:301) - ******** java.lang.Thread.getStackTrace(Thread.java:1426)
Caused by: org.hibernate.exception.GenericJDBCException: Cannot open connection
org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:140)
org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:128)
org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:52)
org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:449)
org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:160)
org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:81)
org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1473)
sun.reflect.GeneratedMethodAccessor378.invoke(Unknown Source)
Caused by: org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot get a connection, pool error Timeout waiting for idle object
org.apache.tomcat.dbcp.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:114)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
org.hibernate.connection.DatasourceConnectionProvider.getConnection(DatasourceConnectionProvider.java:92)
org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:160)
org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:81)
org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1473)
sun.reflect.GeneratedMethodAccessor378.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
Caused by: java.util.NoSuchElementException: Timeout waiting for idle object
org.apache.tomcat.dbcp.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1144)
org.apache.tomcat.dbcp.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:106)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
org.hibernate.connection.DatasourceConnectionProvider.getConnection(DatasourceConnectionProvider.java:92)
org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:160)
org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:81)
org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1473)
sun.reflect.GeneratedMethodAccessor378.invoke(Unknown Source)
Please if have any idea about this help me......
Maybe you have set a timeout for "dead" connections and some queries take longer than that. That means that your pool removed a busy connection as "dead" from the pool and requests another from the DB - until the DB pulls the plug.
To debug this, enable logging for your connection pool, so you can see when it requests new connections.
also check your mysql connection settings. and try to close connection when you are done with your db coz next time(beyond maxConnectionAge limit) that connection state will be dead .
I had such issue before, what you need to do is
close hibernate sessions when you are done with it.
e.g.
Session sess = factory.openSession();
Transaction tx;
try {
tx = sess.beginTransaction();
//do some work
...
tx.commit();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
finally {
sess.close(); // closing session
}

org.hibernate.exception.GenericJDBCException: could not execute query

I am using hibernate 3.6.7 to do mapping. I set the connection part as static.
I need the service program runs forever, and another service will call some methods of this service to query database.
When I leave the service running, the first day it works well but when I call it the next day, it gives:
org.hibernate.exception.GenericJDBCException: could not execute query
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:140)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:128)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.loader.Loader.doList(Loader.java:2545)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276)
at org.hibernate.loader.Loader.list(Loader.java:2271)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:459)
at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:365)
at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1268)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
at com.myCompany.Query.myMethod(Query.java:99)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.ebayopensource.ginger.server.internal.container.MessageProcessor.processRequest(MessageProcessor.java:93)
at org.ebayopensource.ginger.server.container.GingerServletShell.service(GingerServletShell.java:80)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:568)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.sql.SQLException: Closed Connection
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
at oracle.jdbc.driver.PhysicalConnection.prepareStatement(PhysicalConnection.java:864)
at oracle.jdbc.driver.PhysicalConnection.prepareStatement(PhysicalConnection.java:783)
at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:534)
at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:452)
at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:161)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1700)
at org.hibernate.loader.Loader.doQuery(Loader.java:801)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
at org.hibernate.loader.Loader.doList(Loader.java:2542)
It seems the connection gets closed.
Could anyone please give me some suggestion?
Thank you very much:)
Sounds like either the database has closed the connection or some network device has terminated the socket. There are many ways you can work around this problem:
You can issue some sort of "keep alive" type of query (ex: SELECT 1) on the connection every so often to keep it alive. This assumes that it got closed because it was idle.
You can re-open the connection every so often.
If you get a connect closed exception then you can just reopen the connection. Duh.
You can use a connection pool which can do the keep-alive and the reconnection for you. Apache's DBCP is a favorite of many.
I recommend the last one. You would use DBCP something like:
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
ds.setUsername("scott");
ds.setPassword("tiger");
ds.setValidationQuery("SELECT 1"); // this is database specific
ds.setTestWhileIdle(true); // test the connections every so often
ds.setUrl(connectURI);
...
while (!shutdown) {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
...
stmt.close();
// this returns the connection back to the pool instead of really closing
// the connection
conn.close();
}
So instead of passing around a Connection you pass around the BasicDataSource and call getConnection() when you need the connection and conn.close() when you are done with it. The pool does all of the validation work, etc. It also will allow multiple threads to use the database.
Hope this helps.
Edit: You also cannot hold a hibernate session open for a long time. To show you how short lived the session is supposed to be, I'll quote from the docs:
The lifecycle of a Session is bounded by the beginning and end of a logical transaction. (Long transactions might span several database transactions.)
A session holds a database connection so you never want to keep it around for any length of time. You should do a couple of database requests (like a single web request with queries and updates) and then close the session so the underlying database connection can be returned to the pool.
That maybe the structure of the JAVA Model is changed,but the DB table update incorrect! what make the Model and the DB table are not correspondence completely.
You can do like this:
drop the old table
restart the project to rebuild the table
Recently I encountered this error in SpringBoot project.
Reason: Entity class and their respective data in Table had mismatched types. In my case one of the fields which was LocalDate type had value "0000-00-00".
Solution:
In case you are building a new project, drop the old table and restart the project to rebuild the table.
In case your project is old and you do not want to let go of your data, inspect the database table and fix the corresponding value manually.
In my case, I was getting exactly same error when using native Update query.
I resolved this error by using #Modifying (pkg: org.springframework.data.jpa.repository.Modifying) as well as #Transactional annotation (pkg: javax.transaction.Transactional) in repository method.
If we are using Insert, Update, Delete query then #Modifying is required in addition to #Transactional.
#Modifying
#Transactional
#Query(value="Update TBL_EMPLOYEE SET STATUS = :status where ID = :id", nativeQuery = true)
void updateEmployee(#Param("status") String status, #Param("id") String id)

Categories

Resources