java 无法回滚,连接关闭

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32770399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:44:36  来源:igfitidea点击:

Could not rollback, connection closed

javaspringhibernatejpa

提问by logger

Recently I have upgrade all my jar files to the latest version (Spring 4.2.x, JPA and Hibernate)

最近我将所有 jar 文件升级到最新版本(Spring 4.2.x、JPA 和 Hibernate)

Now I am facing some issues with the test cases. Here is the stackTrace of the test...

现在我面临着测试用例的一些问题。这是测试的堆栈跟踪...

org.springframework.transaction.TransactionSystemException: Could not roll back JPA transaction; nested exception is javax.persistence.PersistenceException: unexpected error when rollbacking
    at org.springframework.orm.jpa.JpaTransactionManager.doRollback(JpaTransactionManager.java:548)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:853)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:830)
    at org.springframework.test.context.transaction.TransactionContext.endTransaction(TransactionContext.java:125)
    at org.springframework.test.context.transaction.TransactionalTestExecutionListener.afterTestMethod(TransactionalTestExecutionListener.java:218)
    at org.springframework.test.context.TestContextManager.afterTestMethod(TestContextManager.java:313)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:93)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:86)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:241)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "testConfig.xml" })
@Transactional
@TransactionConfiguration(transactionManager = "test.txManager", defaultRollback = true)
public class ControllerTest {
... logs ... 

    @Autowired
    private Controller controller;
    static final String testIdValue = "114294";
    ... other decorations...

    private Request createRequest() throws Exception {
        Request r = new Request();
        r.setTask(true);
        other set for test values...
        r.assignTaskList(...);
        ...
        return r;
    }

    @Test
    public void assignEndpointsForsSynchTest() throws Exception {

        Request req = createRequest();

        try {
            Response resp = Controller
                    .assignTask(req);
            assertTrue(req.SUCCESSFUL);
        } catch (Exception e) {
            log.info(e.getMessage());
            fail("Unexpected Exception");
        }
    }

}
0(ParentRunner.java:53) at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:229) 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:309) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) Caused by: javax.persistence.PersistenceException: unexpected error when rollbacking at org.hibernate.jpa.internal.TransactionImpl.rollback(TransactionImpl.java:111) at org.springframework.orm.jpa.JpaTransactionManager.doRollback(JpaTransactionManager.java:544) ... 25 more Caused by: org.hibernate.TransactionException: rollback failed at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.rollback(AbstractTransactionImpl.java:217) at org.hibernate.jpa.internal.TransactionImpl.rollback(TransactionImpl.java:108) ... 26 more Caused by: org.hibernate.TransactionException: unable to rollback against JDBC connection at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doRollback(JdbcTransaction.java:167) at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.rollback(AbstractTransactionImpl.java:211) ... 27 more Caused by: java.sql.SQLRecoverableException: Closed Connection at oracle.jdbc.driver.PhysicalConnection.rollback(PhysicalConnection.java:3948) at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doRollback(JdbcTransaction.java:163) ... 28 more

It says the connection is closed....and cannot rollback. does the pool connection from hibernate auto close the connection? Does anyone have any idea on what is the causing of this?

它说连接已关闭......并且无法回滚。来自休眠的池连接是否会自动关闭连接?有没有人知道这是什么原因造成的?

Edit: Test code added (the test is big if more information is needed I will edit again)

编辑:添加了测试代码(如果需要更多信息,测试很大,我会再次编辑)

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

    <bean id="log4jInitialization"
        class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetClass" value="org.springframework.util.Log4jConfigurer" />
        <property name="targetMethod" value="initLogging" />
        <property name="arguments">
            <list>
                <value>classpath:log4j.properties</value>
            </list>
        </property>
    </bean>

    <bean id="test.dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        lazy-init="false">
        <property name="driverClassName" value="org.h2.Driver" />
        <property name="url"
            value="jdbc:h2:mem:test_mem;DB_CLOSE_DELAY=-1;MODE=ORACLE" />
    </bean>

    <jdbc:initialize-database data-source="test.dataSource">
        <jdbc:script location="com/sky/ac/core/engine/comp/schema.sql" />
        <jdbc:script location="com/sky/ac/core/engine/comp/test_data.sql" />
    </jdbc:initialize-database>


    <bean id="test.txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="test.entityMgrFactory" />
        <property name="jpaDialect"> <!-- to support mixed jpaDAO and jdbcTemplateDAO access -->
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
        </property>
    </bean>

    <bean id="test.entityMgrFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="paPersistence" />
        <property name="packagesToScan">
            <list>
                <value>com.sky.ac.core.lock.data</value>
                <value>com.sky.ac.core.vs.dao.jpa</value>
                <value>com.sky.ac.core.sr.data</value>
                <value>com.sky.ac.core.rule.data</value>
                <value>com.sky.ac.core.util.data</value>
                <value>com.sky.ac.core.trace.data</value> 
            </list>
        </property>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="database" value="ORACLE" />
            </bean>
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">false</prop>
                <prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
                <prop key="hibernate.id.new_generator_mappings">true</prop>
                <prop key="hibernate.connection.release_mode">after_statement</prop>
            </props>
        </property>
        <property name="dataSource" ref="test.dataSource" />
    </bean>

    <tx:annotation-driven transaction-manager="test.txManager"/>

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

....bean class defs....

For the xml file

对于 xml 文件

 <dependency>
     <groupId>org.hibernate</groupId>
     <artifactId>hibernate-entitymanager</artifactId>
     <version>4.x.x</version>
 </dependency>

回答by SyntaX

Please stop using H2 in server mode, use it in embedded mode to support @Transactional rollback.

请停止在服务器模式下使用 H2,在嵌入模式下使用它以支持 @Transactional 回滚。

The above exception is thrown because H2 in server mode not supporting Transaction rollback, it is auto-commit by default. Once your query is executed, it is auto-committed and the session is closed. Hence rollback causes the Exception that is thrown.

抛出上述异常是因为服务器模式下的H2不支持事务回滚,默认是自动提交的。执行查询后,它会自动提交并关闭会话。因此回滚导致抛出的异常。

To use H2 in embedded mode, add the jar to classpath and replace the datasource bean by <jdbc:embedded-database id="dataSource" type="H2" />. In your case the value will be id="test.dataSource".

要在嵌入模式下使用 H2,请将 jar 添加到类路径并将数据源 bean 替换为<jdbc:embedded-database id="dataSource" type="H2" />. 在您的情况下,该值将为id="test.dataSource".

Here are some known issues in H2 when used in Server Mode:

以下是 H2 在服务器模式下使用时的一些已知问题:

My recommendation is use a database that well supports transactions with commit and rollback for testing, e.g. MySQL InnoDB.

我的建议是使用能够很好地支持带有提交和回滚的事务的数据库进行测试,例如MySQL InnoDB

Please let me know if you continue to have the Exception even after trying this.

如果您在尝试此操作后仍然出现异常,请告诉我。

回答by André Blaszczyk

There was a quite similar bug in Spring 3.2.2 RELEASE (Jira SPR-10395) with Hibernate 4.2.

在 Spring 3.2.2 RELEASE (Jira SPR-10395) 和 Hibernate 4.2 中存在一个非常相似的错误。

However, you use another Spring version. The issue seems to be in Hibernate Entity Manager.(in 4.2.5 Final version at least).

但是,您使用另一个 Spring 版本。问题似乎出在Hibernate Entity Manager 中。(至少在 4.2.5 最终版中)。

Try to change this Hibernate dependance (upgrade or drowngrade) :

尝试更改此 Hibernate 依赖项(升级或降级):

spring.datasource.connection-test-query=SELECT 1
spring.datasource.test-while-idle=true
spring.datasource.test-on-borrow=true
spring.datasource.validation-interval=10000
spring.datasource.log-validation-errors=true
spring.datasource.validation-query=SELECT 1 

回答by Ravindra babu

Could not roll back JPA transaction; nested exception is javax.persistence.PersistenceException: unexpected error when rollbacking.

无法回滚 JPA 事务;嵌套异常是 javax.persistence.PersistenceException: 回滚时出现意外错误。

it means that there was some disconnection.

这意味着有一些断开连接。

To fix issues with disconnection and make jpa able to recconnect to database server, application.propertiesfile should contain below properties.

要解决断开连接的问题并使 jpa 能够重新连接到数据库服务器,application.properties文件应包含以下属性。

##代码##