Spring - 休眠连接错误

Spring - Hibernate Connection error

当我尝试使用 JUnit 测试 DAO class 时,它抛出以下错误 org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl@1255b1d1 已关闭

我正在使用 Spring 4 和 Hibernate 5,mysql 和 maven

java.lang.IllegalStateException: org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl@1255b1d1 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.rollback(AbstractLogicalConnectionImplementor.java:114)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.rollback(JdbcResourceLocalTransactionCoordinatorImpl.java:239)
    at org.hibernate.engine.transaction.internal.TransactionImpl.rollback(TransactionImpl.java:100)
    at org.springframework.orm.hibernate5.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:608)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.doRollbackOnCommitException(AbstractPlatformTransactionManager.java:900)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:789)
    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.$Proxy20.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.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.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access[=11=]0(ParentRunner.java:58)
    at org.junit.runners.ParentRunner.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-test.xml

<?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.models</value>
                <value>com.timelee.users.models</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>
            </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>

TestUserDao.java

import com.timelee.users.dao.UserDao;
import com.timelee.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
    private UserDao userDao;

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

}

}

UserDaoImpl.java

package com.timelee.users.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.timelee.users.model.User;

@Repository("userDao")
@Transactional
public class UserDaoImpl extends AbstractDao implements UserDao
{
    @Autowired
    private SessionFactory sessionFactory;
public boolean saveUser(User user)
{

    Transaction tx = null;
     Session session=sessionFactory.getCurrentSession();
      try
      {
          tx = session.beginTransaction();
          session.saveOrUpdate(user);
          tx.commit();
          return true;
      }

      catch (Exception e) 
      {
        if (tx!=null) 
            tx.rollback();
        e.printStackTrace();
        return false;
    }

      finally 
      {
          session.close(); 
       }

}


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

      catch (Exception e) 
      {
        if (tx!=null) 
            tx.rollback();
        e.printStackTrace();
    }

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

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

      catch (Exception e) 
      {
        if (tx!=null) 
            tx.rollback();
        e.printStackTrace();
        return null;
    }

      finally 
      {
          session.close(); 
       }

}



public boolean updateUser(User user)
{
    Transaction tx = null;
    Session session = sessionFactory.getCurrentSession();
    try
        {
            tx = session.beginTransaction();
            session.update(user);
            tx.commit();
            return true;
        }

    catch (Exception e)
        {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
            return false;
        }

    finally
        {
            session.close();
        }
}


public boolean deleteUserById(String id)
{
    User user = new User();
    user.setId(id);
    Transaction tx = null;
    Session session = sessionFactory.getCurrentSession();
    try
        {
            tx = session.beginTransaction();
            session.delete(user);
            tx.commit();
            return true;
        }

    catch (Exception e)
        {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
            return false;
        }

    finally
        {
            session.close();
        }
}

}

at org.springframework.transaction.support.AbstractPlatformTransactionManager.doRollbackOnCommitException(AbstractPlatformTransactionManager.java:900)

Spring 测试试图在测试中为您自动执行事务,因此您绝对不需要自己管理任何 JPA/事务。

如果您确实要管理交易,请不要将其标记为 @Transactional

您也可能会从 spring-data-jpa 中受益。它会让你废弃大部分 DAO。