spring 无法提交 Hibernate 事务;嵌套异常是 org.hibernate.Transaction 异常:JDBC 提交失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14520243/
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-09-08 05:39:52  来源:igfitidea点击:

Could not commit Hibernate transaction; nested exception is org.hibernate.Transaction Exception: JDBC commit failed

springhibernateazure-storage

提问by laxman

I am using Windows Azure SQL Server in my application when i connect to application it shows following error.

当我连接到应用程序时,我在我的应用程序中使用 Windows Azure SQL Server,它显示以下错误。

org.springframework.transaction.TransactionSystemException: Could not commit Hibernate transaction; nested exception is org.hibernate.Transaction
Exception: JDBC commit failed
        at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:660)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393
)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.interceptor.CustomizableTraceInterceptor.invokeUnderTrace(CustomizableTraceInterceptor.java:256)
        at org.springframework.aop.interceptor.AbstractTraceInterceptor.invoke(AbstractTraceInterceptor.java:110)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621)
        at com.asman.vote.mypaint.service.UserWorksService$$EnhancerByCGLIB$3137ef.yesterdayWinner(<generated>)
        at com.asman.vote.mypaint.controller.MainController.yesterdayWinner(MainController.java:102)
        at com.asman.vote.mypaint.controller.MainController$$FastClassByCGLIB$$ff981c3a.invoke(<generated>)
        at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
        at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:688)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
        at org.springframework.aop.interceptor.CustomizableTraceInterceptor.invokeUnderTrace(CustomizableTraceInterceptor.java:256)
        at org.springframework.aop.interceptor.AbstractTraceInterceptor.invoke(AbstractTraceInterceptor.java:110)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621)
        at com.asman.vote.mypaint.controller.MainController$$EnhancerByCGLIB$$c20ad12a.yesterdayWinner(<generated>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:
426)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:185)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:151)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:269)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.TransactionException: JDBC commit failed
        at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:161)
        at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:656)
        ... 53 more
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The connection is closed.
        at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.checkClosed(SQLServerConnection.java:388)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.commit(SQLServerConnection.java:1936)
        at org.hibernate.transaction.JDBCTransaction.commitAndResetAutoCommit(JDBCTransaction.java:170)
        at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:146)
        ... 54 more

Hibernate.cfg.xml:

Hibernate.cfg.xml:

..................

..................

<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
        <property name="hibernate.connection.password">Asman.1234</property>`

        <property name="hibernate.connection.url">jdbc:sqlserver://mzfoe7t5fn.database.windows.net:1433;databaseName=VOTEMYPAINT;encrypt=false;packetSize=10240;loginTimeout=300</property>
        <property name="hibernate.connection.username">SQLAdmin@mzfoe7t5fn</property>
        <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
        <property name="hibernate.search.autoregister_listeners">false</property>
        <property name="hibernate.c3p0.min_size">5</property>

        <mapping class="com.asman.vote.mypaint.to.UserProfile" />
        <mapping class="com.asman.vote.mypaint.to.Purchasedetails" />
        <mapping class="com.asman.vote.mypaint.to.Topics" />
        <mapping class="com.asman.vote.mypaint.to.AgeGroups" />
        <mapping class="com.asman.vote.mypaint.to.Admin" />
        <mapping class="com.asman.vote.mypaint.to.TodaysTopic" />
        <mapping class="com.asman.vote.mypaint.to.UserWorks" />
        <mapping class="com.asman.vote.mypaint.to.Htmlpages" />
    </session-factory>
</hibernate-configuration>

Hibernate-context.html:

Hibernate-context.html:

<?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:p="http://www.springframework.org/schema/p" 
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">`
<context:property-placeholder location="/WEB-INF/spring.properties" />

    <!-- Enable annotation style of managing transactions -->
    <tx:annotation-driven transaction-manager="transactionManager" />   

    <!-- Declare the Hibernate SessionFactory for retrieving Hibernate sessions -->
    <!-- See http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/orm/hibernate3/annotation/AnnotationSessionFactoryBean.html -->                           
    <!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/SessionFactory.html -->
    <!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/Session.html -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"

                 p:configLocation="${hibernate.config}"
                 p:packagesToScan="com.asman.vote.mypaint"/>
    <!-- p:dataSource-ref="dataSource" -->
    <!-- Declare a datasource that has pooling capabilities--> <!-- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
                destroy-method="close"
                p:driverClass="${app.jdbc.driverClassName}"
                p:jdbcUrl="${app.jdbc.url}"
                p:user="${app.jdbc.username}"
                p:password="${app.jdbc.password}"
                p:acquireIncrement="10"
                p:idleConnectionTestPeriod="60"
                p:maxPoolSize="100000"
                p:maxStatements="100"
                p:minPoolSize="100000" /> --><bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" 
                p:sessionFactory-ref="sessionFactory" /></beans>

applicationContext.xml:

应用上下文.xml:

http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">`

http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">`

<!-- <context:property-placeholder properties-ref="deployProperties" /> -->

<!-- Activates various annotations to be detected in bean classes -->
<context:annotation-config />

<!-- Scans the classpath for annotated components that will be auto-registered as Spring beans.
 For example @Controller and @Service. Make sure to set the correct base-package -->
<context:component-scan base-package="com.asman.vote.mypaint" />

<!-- Configures the annotation-driven Spring MVC Controller programming model.
Note that, with Spring 3.0, this tag works in Servlet MVC only!  -->
<mvc:annotation-driven /> 

<!-- Configure the multipart resolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
    p:maxUploadSize="100000000"/>

<mvc:resources mapping="/resources/**" location="/resources/" /> 
<mvc:interceptors>
<bean class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
    <property name="sessionFactory">
        <ref local="sessionFactory" />
    </property>
</bean></mvc:interceptors><!-- Imports logging configuration -->
<import resource="trace-context.xml"/>
<import resource="hibernate-context.xml" /> 
<bean id="deployProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"
    p:location="/WEB-INF/spring.properties" /></beans> 

spring-servlet.xml:

弹簧servlet.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:p="http://www.springframework.org/schema/p" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

    <!-- Declare a view resolver -->
    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
            p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="1"/>

</beans>

trace-context.xml:

跟踪上下文.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:p="http://www.springframework.org/schema/p" 
        xmlns:aop="http://www.springframework.org/schema/aop"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/aop 
            http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">`

    <!-- For parsing classes with @Aspect annotation -->
    <aop:aspectj-autoproxy/>

    <bean id="customizableTraceInterceptor" class="com.asman.vote.mypaint.aop.TraceInterceptor"
        p:enterMessage="Entering $[targetClassShortName].$[methodName]($[arguments])"
        p:exitMessage="Leaving $[targetClassShortName].$[methodName](): $[returnValue]"/>

    <aop:config>
      <aop:advisor advice-ref="customizableTraceInterceptor" pointcut="execution(public * com.asman.vote.mypaint.service..*(..))"/>
      <aop:advisor advice-ref="customizableTraceInterceptor" pointcut="execution(public * com.asman.vote.mypaint.controller..*(..))"/>
    </aop:config>

</beans>

回答by arpit sharma

I have had a similar error, the easiest solution is to add @Transaction with @Transactional(propagation = Propagation.REQUIRES_NEW)

我有一个类似的错误,最简单的解决方案是添加 @Transaction 和 @Transactional(propagation = Propagation.REQUIRES_NEW)

You will not get this error after that and would work perfectly.

之后您将不会收到此错误,并且可以完美运行。

回答by Amit Kumar

The reason for this is that you have opened a hibernate session & you are trying to execute two queries but remember commit of first transaction will not be appearing before start of other. This might be helpful. Try to run other query when one transaction commits or use criteria.

这样做的原因是您打开了一个休眠会话,并且您正在尝试执行两个查询,但请记住,第一个事务的提交不会在其他事务开始之前出现。这可能会有所帮助。当一个事务提交或使用条件时,尝试运行其他查询。

回答by Harshad_Kenjale

use @Transactional above the serviceimpl method

在 serviceimpl 方法上方使用 @Transactional

回答by Neeraj Gahlawat

You're using @Transactional, to have Spring start, commit and rollback transactions for you, and handle your transactions declaratively. The whole point of this is precisely to not have to start, commit and rollback transactions in the code. So the method implementation should simply be

您正在使用@Transactional,让 Spring 为您启动、提交和回滚事务,并以声明方式处理您的事务。这样做的重点正是不必在代码中启动、提交和回滚事务。所以方法实现应该只是

return (List<Login>) sessionFactory.getCurrentSession().createQuery("from Login").list();