【问题标题】:spring hibernate manual commit春季休眠手动提交
【发布时间】:2013-04-03 03:37:30
【问题描述】:

有人可以帮忙吗?

目前我遇到了一些问题,我正在使用 spring、jpa、hibernate。 这是问题所在,当我尝试保存几个对象,然后像 solrj 返回​​ false 时手动回滚。

我尝试了以下方法:
1。用户事务(例外:Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException

2.entitymanager.gettransaction().begin(例外:共享管理器)

谢谢,如果你能帮我弄清楚。

标题:

@Service("jpaWallPostService")
@Repository
public class WallPostServiceImpl implements WallPostService {
    //........
    @PersistenceContext
    private EntityManager em;

========================================

  @Transactional(readOnly=false)
public boolean save(String solrURL,int userid,wall_post wallPost,List<String> groupsid,List<String> hashtag){


    try{
        em.getTransaction().begin();// ***error occur on here*** and stop here
        //...............proccess
        boolean ok = SolrJ.IndexingWallPost(solrURL,userid, wallPost.getTitle(), wallPost.getMessage(), hashtag,groupsid);
        if(!ok)
            em.getTransaction().rollback();



        em.getTransaction().commit();
        return true;
    }
    catch(Exception e)
    {
        em.getTransaction().rollback();
        return false;
    }
}

这是错误日志

SEVERE: Servlet.service() for servlet [appServlet] in context with path [/opscentral] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead] with root cause
java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:198)
    at $Proxy42.getTransaction(Unknown Source)
    at sg.com.innovax.opscentralv5.table.service.impl.WallPostServiceImpl.save(WallPostServiceImpl.java:230)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:319)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at $Proxy49.save(Unknown Source)
    at sg.com.innovax.opscentralv5.UserHomeController.newWall_post(UserHomeController.java:171)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:311)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:101)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:146)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:173)
    at org.springframework.security.config.debug.DebugFilter.doFilterInternal(DebugFilter.java:45)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

【问题讨论】:

  • 发布完整的错误日志

标签: spring hibernate jpa transactions rollback


【解决方案1】:

正确的方法是在使用@Transactional 时删除所有手动事务管理。在适当的 CMT 上下文中,您不应手动与事务交互,@transactional 确保您的方法将在事务中运行,将传播事务上下文以委托调用,并将在执行结束时提交或在抛出异常的情况下回滚.您唯一可以做的就是在EJBContext 上使用setRollbackOnly() 强制回滚

见:is there a way to force a transactional rollback without encountering an exception?

否则,如果您更喜欢手动管理事务:

使用你的 entityManagerFactory 在你的 spring 上下文中定义一个 transactionManager bean。

 <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
 </bean>

并以这种方式使用它:

@Inject
JpaTransactionManager txManager;

DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName("rootTransaction");
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus status = txManager.getTransaction(def);
[...]
txManager.commit(status);

【讨论】:

  • 我原来确实设置了transactionmanager....甚至没有启动,然后出错。所以其余代码在错误提示后不会运行
  • 您如何管理注释处理?难道你没有这样的东西:
  • 然后呢?如果您在 bean 中注入 transactionManager 并在其上调用 .commit() 会发生什么问题?
  • 原帖上的错误---(不允许在共享的EntityManager上创建事务-改用Spring事务或EJB CMT)
  • First---Gab,你很有帮助,谢谢 :) 刚才我尝试抛出 RuntimeException,它起作用了,它回滚了记录。以前不起作用,这是因为我确实尝试捕获异常已经消耗的异常。然而,虽然它可以工作(通过抛出异常),但我认为这不是一个好主意和正确的方法。我现在就试试你的方法:)
【解决方案2】:

问题是您的保存方法被注释为 Transactional,这意味着事务将由 Spring 处理,但在该方法中,您尝试使用 JPA API 以编程方式管理事务。

所以你错误地混合了两种方法。理想情况下,您应该只使用 Transactional 注释。

下面我添加了处理此问题的 Spring 辅助类的源代码。相关类是org.springframework.orm.jpa.SharedEntityManagerCreator。它有一个私有静态类SharedEntityManagerInvocationHandler,抛出错误的相关代码如下

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  .....
  .....
  else if (method.getName().equals("getTransaction")) {
      throw new IllegalStateException("Not allowed to create transaction on shared"
                             +" EntityManager - use Spring transactions or EJB CMT instead");
.....
.....
  }

这就是我上面提到的。

您正在调用 getTransaction 方法并收到错误消息。

所以摆脱方法内部的事务处理,只坚持 Transactional 注释。

【讨论】:

  • 是的,你的方法体应该像这样boolean ok = SolrJ.IndexingWallPost(solrURL,userid, wallPost.getTitle(), wallPost.getMessage(), hashtag,groupsid); if(!ok) // throw some RuntimeException;
  • 根据我的研究和理解,我同意您的观点。我猜春天正在占据交易,我试图得到并控制它。但是我只是删除了@Transactional 并尝试获取事务,然后我遇到了这个问题(“java.lang.IllegalStateException:不允许在共享 EntityManager 上创建事务 - 改用 Spring 事务或 EJB CMT”)
  • orid---你的方法是可行的,但只是为了确保不要在这个区域内尝试和捕捉,否则我会遇到同样的问题。谢谢!
猜你喜欢
  • 2013-05-04
  • 2015-06-30
  • 1970-01-01
  • 2020-05-17
  • 1970-01-01
  • 2013-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多