Tuesday, February 12, 2013

Spring - Could not open Hibernate Session for transaction

This happens when the Spring application is idle for a while and a user tries to log in to the application.

The message is as follows:
Could not open Hibernate Session for transaction; nested exception is org.hibernate.TransactionException: JDBC begin failed
 Subsequent logins after the first login failure would sucede.

This has to do with stale database connections. There are connections killed by the server that are still considered to be alive by the connection pool.

There are two solutions:

  1. set minimum connection pool size to zero
  2. set "testonborrow"
"testonborrow" will also test if the connection is alive prior to issuing the desired query.

To implement any of the above, you can use c3p0 or Apache's dbcp library.

The following will demonstrate "testonborrow":

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxActive" value="100"/>
        <property name="maxWait" value="1000"/>
        <property name="poolPreparedStatements" value="true"/>
        <property name="defaultAutoCommit" value="true"/>
        <property name="validationQuery" value="SELECT 1" />
        <property name="testOnBorrow" value="true" />
</bean>

1 comment:

  1. I have read your article, it is very informative and helpful for me.I admire the valuable information you offer in your articles. Thanks for posting it..
    Minecraft Server List

    ReplyDelete