【问题标题】:getting deadlock while trying to execute findAll() using jpa for MySql database尝试使用 jpa for MySql 数据库执行 findAll() 时出现死锁
【发布时间】:2020-04-14 12:35:02
【问题描述】:

我正在使用 JPA (Spring RepositoryRestResource) 进行持久化,数据库是 Mysql。当我从 UI 调用 GET API 时,它调用 (WorkflowServiceImpl.getActivities()) 方法。它只有 JPA 的findAll() 方法来获取数据列表。但是我在拨打这个电话时看到了死锁问题。

我的问题是,当它所做的只是获取并且没有执行更新语句时,为什么它会陷入死锁状态?请帮我解决这个问题?

getActivities() 的代码

@Override
public Map<String, WorkflowTemplateDTO> getActivities() {
    //adding all activities
    return workflowTemplateRepository.findAll().stream()
            .map(workflowTemplate -> {
                Set<DefinitionType> pageTypes = getAllPagesOfWorkflow(workflowTemplate).stream()
                        .map(PageTemplate::getType)
                        .collect(Collectors.toSet());

                return workflowTemplate.toWorkflowTemlateDTO(pageTypes);
            })
            .collect(Collectors.toMap(WorkflowTemplateDTO::getId, Function.identity()));
}


public List<PageTemplate> getAllPagesOfWorkflow(WorkflowTemplate workflowTemplate) {
    return workflowPageRepository.findAllByWorkflowTemplate(workflowTemplate).stream()
            .map(WorkflowPage::getPageTemplate).collect(Collectors.toList());
}

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/serve_mar
spring.datasource.username=root
spring.datasource.password=

spring.jpa.database-platform=org.hibernate.dialect.MySQL57Dialect
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=update

错误日志

org.springframework.dao.CannotAcquireLockException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.LockAcquisitionException: could not execute statement
        at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:287)
        at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:253)
        at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:536)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:746)
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:714)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:534)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:305)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
        at com.tfsc.ilabs.selfservice.workflow.services.impl.WorkflowServiceImpl$$EnhancerBySpringCGLIB$$f31a06d8.getActivities(<generated>)
        at com.tfsc.ilabs.selfservice.workflow.controllers.WorkflowController.getWorkflowTemplates(WorkflowController.java:38)
        at com.tfsc.ilabs.selfservice.workflow.controllers.WorkflowController$$FastClassBySpringCGLIB$$c029c43e.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
        at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
        at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:56)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:88)
        at com.tfsc.ilabs.selfservice.common.controller.ControllerLoggingAspect.profile(ControllerLoggingAspect.java:39)
        at jdk.internal.reflect.GeneratedMethodAccessor185.invoke(Unknown Source)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:644)
        at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:633)
        at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:55)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:62)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
        at com.tfsc.ilabs.selfservice.workflow.controllers.WorkflowController$$EnhancerBySpringCGLIB$$bddfbb1b.getWorkflowTemplates(<generated>)
        at jdk.internal.reflect.GeneratedMethodAccessor225.invoke(Unknown Source)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
        at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
        at com.tfsc.ilabs.selfservice.security.config.SessionValidationFilter.doFilter(SessionValidationFilter.java:52)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
        at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
        at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
        at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:836)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1747)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.base/java.lang.Thread.run(Thread.java:834)
    Caused by: org.hibernate.exception.LockAcquisitionException: could not execute statement
        at org.hibernate.dialect.MySQLDialect$3.convert(MySQLDialect.java:546)
        at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
        at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
        at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
        at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:178)
        at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3360)
        at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3233)
        at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3634)
        at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:146)
        at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
        at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:478)
        at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:356)
        at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
        at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1454)
        at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:511)
        at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3290)
        at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2486)
        at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:473)
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:178)
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:39)
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:271)
        at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:104)
        at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:532)
        ... 114 common frames omitted
    Caused by: com.mysql.cj.jdbc.exceptions.MySQLTransactionRollbackException: Deadlock found when trying to get lock; try restarting transaction
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:123)
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
        at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
        at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:955)
        at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1094)
        at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1042)
        at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1345)
        at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1027)
        at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
        at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)
        at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)
        ... 132 common frames omitted

实体文件

package com.tfsc.ilabs.selfservice.page.models;

import com.tfsc.ilabs.selfservice.common.models.AuditableEntity;
import com.tfsc.ilabs.selfservice.common.models.DefinitionType;
import com.tfsc.ilabs.selfservice.common.utils.PageConverter;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Objects;

@Entity
public class PageTemplate extends AuditableEntity {
    @Id
    @NotNull
    @Column(unique = true)
    private String id;

    @NotNull
    private String title;

    @Column(length = 1024)
    private String description;

    @NotNull
    @Column(columnDefinition = "mediumtext")
    @Convert(converter = PageConverter.class)
    private PageDefinition definition;

    @NotNull
    @Enumerated(EnumType.STRING)
    @Column(length = 45)
    private DefinitionType type;

    public PageTemplate() {
        // for jackson purpose onlypage
    }

    public PageTemplate(@NotNull String id, @NotNull String title, String description, PageDefinition definition,
            DefinitionType type) {
        this.id = id;
        this.title = title;
        this.description = description;
        this.definition = definition;
        this.type = type;
    }

    public DefinitionType getType() {
        return type;
    }

    public void setType(DefinitionType type) {
        this.type = type;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public PageDefinition getDefinition() {
        return definition;
    }

    public void setDefinition(PageDefinition definition) {
        this.definition = definition;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;
        PageTemplate that = (PageTemplate) o;
        return Objects.equals(title, that.title) && Objects.equals(description, that.description)
                && Objects.equals(definition, that.definition) && Objects.equals(type, that.type);
    }

    @Override
    public int hashCode() {
        return Objects.hash(title, description, definition, type);
    }

    @Override
    public String toString() {
        return "PageTemplate{" + "id=" + id + ", title='" + title + '\'' + ", description='" + description + '\''
                + ", definition='" + definition + '\'' + ", type='" + type + '\'' + '}';
    }
}

我从日志中观察到,对于 PageTemplate.java 实体类的每个findAll()findById() 调用1 个选择和1 个更新sql 由休眠执行。我不确定为什么?这只发生在这个特定实体上,而对于所有其他实体,它只执行 1 个 select 语句。

2020-04-15 01:43:54,551 INFO com.tfsc.ilabs.selfservice.common.controller.ControllerLoggingAspect [http-nio-8090-exec-7] received rest call at com.tfsc.ilabs.selfservice.workflow.controllers.WorkflowController.pageTemplate with arguments [chathours_p0]
Hibernate: select pagetempla0_.id as id1_15_0_, pagetempla0_.created_by as created_2_15_0_, pagetempla0_.created_on as created_3_15_0_, pagetempla0_.last_updated_by as last_upd4_15_0_, pagetempla0_.last_updated_on as last_upd5_15_0_, pagetempla0_.definition as definiti6_15_0_, pagetempla0_.description as descript7_15_0_, pagetempla0_.title as title8_15_0_, pagetempla0_.type as type9_15_0_ from page_template pagetempla0_ where pagetempla0_.id=?
Hibernate: update page_template set last_updated_by=?, last_updated_on=?, definition=?, description=?, title=?, type=? where id=?
2020-04-15 01:43:54,609 INFO com.tfsc.ilabs.selfservice.common.controller.ControllerLoggingAspect [http-nio-8090-exec-7] rest call at com.tfsc.ilabs.selfservice.workflow.controllers.WorkflowController.pageTemplate returning response PageTemplate{id=chathours_p0, title='Operational Hours', description='Operational Hours', definition='com.tfsc.ilabs.selfservice.page.models.PageDefinition@1199f9f', type='UPDATE'}, Method execution time 58 milliseconds

有解决此问题的建议吗?

【问题讨论】:

    标签: mysql hibernate spring-boot spring-data-jpa


    【解决方案1】:

    Java 流在Collect 等终端操作上工作,因此会发生死锁。 在您使用结果查询其他数据之前,这里workflowTemplateRepository.findAll() 尚未获取。避免在 stream map() 中调用存储库以防止死锁。

    你可以试试这个方法防止死锁

    @Override
    public Map<String, WorkflowTemplateDTO> getActivities() {
        //adding all activities
        List<WorkflowTemplate> workflowTemplates = workflowTemplateRepository.findAll();
        Map<String, WorkflowTemplateDTO>  mp = new HashMap<String, WorkflowTemplateDTO>();
        for(WorkflowTemplate workflowTemplates : workflowTemplates) {
             Set<DefinitionType> pageTypes = getAllPagesOfWorkflow(workflowTemplate).stream()
                            .map(PageTemplate::getType)
                            .collect(Collectors.toSet());
            WorkflowTemplateDTO workflowTemplateDTO = workflowTemplate.toWorkflowTemlateDTO(pageTypes);
            mp.put(workflowTemplateDTO.getId(),workflowTemplateDTO )
        }
        return workflowTemplates;
    }
    
    
    public List<PageTemplate> getAllPagesOfWorkflow(WorkflowTemplate workflowTemplate) {
        return workflowPageRepository.findAllByWorkflowTemplate(workflowTemplate).stream()
                .map(WorkflowPage::getPageTemplate).collect(Collectors.toList());
    }
    

    【讨论】:

    • 这不起作用,我观察到当我为一个实体(PageTemplate)调用 findAll() 时,hibernate 正在为每个 select 语句执行 1 个更新语句。我已经更新了描述。知道为什么当我执行 findById() 或 findAll() 时休眠会执行更新。
    • @sushil 它不起作用意味着什么?又发生了死锁?
    • 可能不会再次发生死锁,如果您有任何逻辑问题,那么这不是我解决方案的一部分。 (因为你没有描述你想做什么操作)
    • 由于更新语句与 repositotyRestResource 的 findById() 方法一起执行而发生死锁。早些时候我在服务类的类级别有@Transactional,现在我将@Transactional 移动到方法级别,仅用于所需的方法。并解决了这个死锁问题。
    • 你连服务细节都不贴,我们怎么知道你在用什么。祝你好运
    【解决方案2】:

    查询会触发尚未持久化的更改刷新。 您需要识别更改并查看它们导致死锁的原因。

    【讨论】:

    • 知道如何识别尚未刷新的更改吗?这些事务不是由 jpa 管理吗,调用失败的 API 来加载主页元素,直到没有事务被启动。
    • 我会检查您是否可以在连接上添加/激活日志记录以查看所有 sql 语句。还可以使用调试器检查 EntityManager 中的第一级缓存。顺便说一句:我认为 Abinash 可能是对的。
    猜你喜欢
    • 2017-02-07
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多