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();
        }
    }

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

  • 相关阅读:
    获取iframe中的元素
    用npm安装express后express命令找不到
    Openfire 单人聊天和多人聊天(发送消息、接收消息)
    openfire拦截数据包与发送广播
    xmpp with openfire 插件-利用Broadcast实现群
    Smack 结合 Openfire服务器,建立IM通信,发送聊天消息
    openfire默认数据库与应用系统数据库整合
    ios即时通讯客户端开发之-mac上安装MySQL
    ios即时通讯客户端开发之-mac上搭建openfire服务器
    IOS block使用中碰到的一个小坑
  • 原文地址:https://www.cnblogs.com/acm-bingzi/p/cubaManager.html
Copyright © 2011-2022 走看看