How to fix the org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl@779de014 is closed issue
Asked Answered
Q

4

7

I am trying to create or update user with Hibernate 5 and it throws following exception: org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl@779de014 is closed

I'm using the following technologies:

  • Spring 4
  • Hibernate 5
  • Maven
  • Eclipse

This is my UserDaoImpl.Java:

package com.fasttrack.users.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.fasttrack.users.model.User;

@Repository
@Transactional
public class UserDaoImpl extends AbstractDao implements UserDao
{
    @Autowired
    private SessionFactory sessionFactory;
    public boolean saveUser(User user)
    {
         Session session=sessionFactory.getCurrentSession();
          try
          {
             session.persist(user);
             return true;
          }

          catch (Exception e) 
          {

            e.printStackTrace();
            return false;
        }

          finally 
          {
              session.close(); 
           }

    }


    @SuppressWarnings("unchecked")
    public List<User> getUsers()
    {
         List<User> users;
         Session session=sessionFactory.getCurrentSession();
          try
          {
              users=(List<User>) session.createQuery("FROM USER"); 
              return users;
          }

          catch (Exception e) 
          {
            e.printStackTrace();
        }

          finally {
              session.close(); 
           }
        return null;
    }

    public User getUser(String id)
    {
         User user;
         Session session=sessionFactory.getCurrentSession();
          try
          {
              user=(User)session.get(User.class,id); 
              return user;
          }

          catch (Exception e) 
          {
            e.printStackTrace();
            return null;
        }

          finally 
          {
              session.close(); 
           }

    }



    public boolean updateUser(User user)
    {
        Session session = sessionFactory.getCurrentSession();
        try
            {
                session.saveOrUpdate(user);
                return true;
            }

        catch (Exception e)
            {
                e.printStackTrace();
                return false;
            }

        finally
            {
                session.close();
            }
    }


    public boolean deleteUserById(String id)
    {
        User user = new User();
        user.setId(id);

        Session session = sessionFactory.getCurrentSession();
        try
            {
                session.delete(user);
                return true;
            }

        catch (Exception e)
            {
                e.printStackTrace();
                return false;
            }

        finally
            {
                session.close();
            }
    }

}

This is my TestUserDao.java:

import com.fasttrack.users.dao.UserDao;
import com.fasttrack.users.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/Hibernate-test.xml")

public class TestUserDao
{
    @Autowired(required=true)
    public UserDao userDao;

    @Test
    public void testSaveUser()
    {
        User user=new User();
        user.setFirstName("TestUser1");
        boolean result=userDao.saveUser(user);
    }
}

Error Message:

Mar 01, 2017 1:14:52 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getDefaultTestExecutionListenerClassNames
INFO: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
Mar 01, 2017 1:14:52 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getTestExecutionListeners
INFO: Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@6be46e8f, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@3567135c, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@327471b5, org.springframework.test.context.support.DirtiesContextTestExecutionListener@4157f54e, org.springframework.test.context.transaction.TransactionalTestExecutionListener@90f6bfd, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@47f6473]
Mar 01, 2017 1:14:52 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Hibernate-test.xml]
Mar 01, 2017 1:14:53 PM org.springframework.context.support.GenericApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext@2a5ca609: startup date [Wed Mar 01 13:14:53 EST 2017]; root of context hierarchy
Mar 01, 2017 1:14:53 PM org.springframework.context.support.PropertySourcesPlaceholderConfigurer loadProperties
INFO: Loading properties file from class path resource [database.properties]
Mar 01, 2017 1:14:53 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Mar 01, 2017 1:14:53 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.6.Final}
Mar 01, 2017 1:14:53 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Mar 01, 2017 1:14:53 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Mar 01, 2017 1:14:54 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Mar 01, 2017 1:14:54 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Mar 01, 2017 1:14:54 PM org.springframework.orm.hibernate5.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.apache.commons.dbcp.BasicDataSource@130d63be] of Hibernate SessionFactory for HibernateTransactionManager
Generated Id: USER0
Mar 01, 2017 1:14:55 PM org.springframework.orm.hibernate5.HibernateTransactionManager doRollbackOnCommitException
SEVERE: Commit exception overridden by rollback exception
java.lang.IllegalStateException: org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl@6b410923 is closed
    at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.errorIfClosed(AbstractLogicalConnectionImplementor.java:37)
    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:128)
    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:247)
    at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.commit(AbstractLogicalConnectionImplementor.java:79)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:221)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
    at org.springframework.orm.hibernate5.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:582)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:504)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy31.saveUser(Unknown Source)
    at TestUserDao.testSaveUser(TestUserDao.java:23)
    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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Hibernate xml file:

<?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:context="http://www.springframework.org/schema/context"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
                            http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">


    <context:property-placeholder location="classpath:database.properties" />
      <context:component-scan  base-package="com.timelee.*" />


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


     <!--  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  -->

     <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
       <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}"/>

    </bean>



    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan">
            <list>
                <value>com.timelee.timesheet.model</value>
                <value>com.timelee.users.model</value>
                <value>com.timelee.*</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql:false}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql:false}</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>       
    </bean>

    <bean id="transactionManager"  class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="persistenceExceptionTranslationPostProcessor"
        class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

</beans>
Quadrangle answered 1/3, 2017 at 18:1 Comment(1)
Please share the Hibernate-test.xml contents.Leannleanna
O
17

I found something strange in your error message "SEVERE: Commit exception overridden by rollback exception". If you look at the try block in UserDaoImpl.Java file you have return statement, which closes the hibernate connection before returning. And you have session.close() statement in finally block which doesn't make sense, since the connection was already closed. Would you mind removing session.close() statement and try again. Let me know if this solves your problem.

Overkill answered 19/5, 2017 at 0:5 Comment(1)
closing the session before returning Object also leads the same failure to me, thanks.Erlandson
O
3

As explained in the Spring Framework User Guide, in a @Transactional block, you don't need to manually manage the Hibernate Session since the TransactionInterceptor does that for you.

So, instead of:

@SuppressWarnings("unchecked")
public List<User> getUsers() {
    List<User> users;
    Session session=sessionFactory.getCurrentSession();
    try
    {
        users=(List<User>) session.createQuery("FROM USER"); 
        return users;
    }
    catch (Exception e) 
    {
        e.printStackTrace();
    }
    finally {
      session.close(); 
    }
    return null;
}

you should do this:

@SuppressWarnings("unchecked")
public List<User> getUsers() {
    try {
        return sessionFactory.getCurrentSession()
        .createQuery("FROM USER")
        .getResultList(); 
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Aside from removing the session.close call, there were more issues that I fixed in your example:

  1. You were not calling getResultList() on the Hibernate Query which, instead, you cast to List<User>
  2. Calling e..printStackTrace(); is bad. You should use a Logger framework instead. In this case, it's better to propagate the exception further instead of hiding it under the carpet.
  3. Why would you return null when you expect a List? If there is no result, and empty List is a much better alternative. In your example, when you got an exception, you'd return null which it's indistinguishable from the case when you'd get an empty result set.
Organotherapy answered 5/6, 2017 at 9:31 Comment(8)
getCurrentSession() may not work everywhere; Since session object is not thread safe. So what about openSession() per request in a multi threaded environment?Hindmost
Use Spring transaction and Session handling instead of doing it manually via openSession.Organotherapy
Would you please guide me through using it?Hindmost
The Spring documentation is the right resource to guide you.Organotherapy
What about using this in the Hibernate conf: <property name="hibernate.current_session_context_class">thread</property> ?????Hindmost
Don't use that! Check out the Spring and Hibernate documentation for more details.Organotherapy
I found no suggestion of not using it in Hibernate doc! docs.jboss.org/hibernate/orm/5.4/userguide/html_single/…Hindmost
Try the Spring documentation as well.Organotherapy
J
2

I stumbled over a quite similar stack trace when updating a legacy application to Hibernate 5 / Spring 4 and implementing transaction support while I was at it.

We are using two database connections (two SessionFactories and two TransactionManagers).

The problem was that I nested a transaction on connection B inside a transaction on connection A. Like this:

apiCall
  -> @Transactional 
     doSomethingWithConnectionA
     -> @Transactional
        doSomethingWithConnectionB

The issue was gone, when I excuted the functions one after the other from the same level

apiCall
  -> @Transactional 
     doSomethingWithConnectionA
  -> @Transactional
     doSomethingWithConnectionB
Johppa answered 18/3, 2017 at 15:25 Comment(1)
I do not have redundant Transactional in my code as shown aboveQuadrangle
S
0

I also had a similar problem, and realised that I was accidentally closing a hibernate session manually within a @Transactional context. This is what I was doing:

public Collection<E> findAllByIds(Collection<ID> ids) {
    try (var session = entityManager.unwrap(Session.class)) {
      return session
          .byMultipleIds(myClass)
          .withBatchSize(batchSize)
          .multiLoad(ids.stream().toList());
    }
  }

@Transactional
public void doSomeSave(Collection<E> entities) {
    this.findAllByIds(getIds(entities));
    
    // do the rest of the transaction process

    this.saveAll(entities);
}

Using a Session inside a "try-with-resource" block would cause that specific transaction to be closed once the query is done, and using that inside another Transactional block doesn't make sense because then it can't do the whole transaction atomically.

Removing the try-with-resource block solved the problem.

Streusel answered 6/5, 2024 at 15:49 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.