zoukankan      html  css  js  c++  java
  • 一个开启多个事务导致OptimisticLockException异常的问题

      异常信息:org.eclipse.persistence.exceptions.OptimisticLockException
      对象在其他的事物中被修改,而造成这一个问题的原因是:同时开启了两个事务,修改了同一个对象。解决方式就是:让对象在同一个事务中修改


      我使用的是cuba框架,这个框架可以使用 DataManager 来操作数据,也可以使用JPA的 EntityManager ,而DataManager每次执行都会新起一个事务。
      就是因为开始不懂这些,以为这两个是同一回事,才出了错。

    错误示例

      首先使用了EntityManager查询了对象,然后又使用DataManager新开了事务进行提交,这样会报错

    public void backEnd(UUID entityId) {
        Transaction tx = persistence.getTransaction();
        try {
            EntityManager em = persistence.getEntityManager();
            ExcelTable excelTable = em.find(ExcelTable.class, entityId);
            ProcInstance procInstanceNormal = ProcUtils.findProcInstanceNoDel(dataManager,excelTable);
            if(procInstanceNormal != null){
                procInstanceNormal.setDescription("【销毁申请】已完成");
                dataManager.commit(procInstanceNormal);
            }
            tx.commit();
        } catch (Exception e) {
            logger.error("删除流程excelTable " + entityId + "发生错误:" + e.getMessage());
        } finally {
            tx.end();
        }
    }

    正确用法

      修改成只使用EntityManager来修改对象就没有问题了。 

    @Inject
    private Persistence persistence;
    @Inject
    private DataManager dataManager;
    public void backEnd(UUID entityId) {
        Transaction tx = persistence.getTransaction();
        try {
            EntityManager em = persistence.getEntityManager();
            ExcelTable excelTable = em.find(ExcelTable.class, entityId);
            ProcInstance procInstanceNormal = ProcUtils.findProcInstanceNoDel(dataManager,excelTable);
            if(procInstanceNormal != null){
                procInstanceNormal.setDescription("【销毁申请】已完成");
                em.merge(procInstanceNormal);
                em.flush();
            }
            tx.commit();
        } catch (Exception e) {
            logger.error("删除流程excelTable " + entityId + "发生错误:" + e.getMessage());
        } finally {
            tx.end();
        }
    }

    原创文章,欢迎转载,转载请注明出处!

  • 相关阅读:
    leetcode 1140. Stone Game II
    主席树
    Codeforces Round #442 (Div. 2) E Danil and a Part-time Job (dfs序加上一个线段树区间修改查询)
    UVALive 3942 Remember the Word
    UVA 11235 Frequent values (RMQ )
    CodeForces
    hdu 2955 Robberies (01背包好题)
    hdu 1054 Strategic Game (简单树形DP)
    hdu 5532 Almost Sorted Array (水题)
    hdu 2089 不要62 (数位dp基础题)
  • 原文地址:https://www.cnblogs.com/acm-bingzi/p/cubaManager.html
Copyright © 2011-2022 走看看