java merge_java – OptimisticLockException当使用JPA merge()

本文探讨了在Java应用程序中使用JPA更新实体时遇到的乐观锁定异常问题。具体表现为调用`em.find()`时意外触发了数据库对象的更新,导致后续合并操作因版本不匹配引发`OptimisticLockException`。解决方案是先分离实体,避免`find`方法更新版本。同时,文章指出直接复制新对象属性到现有对象并使用现有对象进行合并可以避免这个问题。
摘要由CSDN通过智能技术生成

我有一个休息的应用程序,其中一个资源可以更新.以下是负责实现此任务的两种方法:

> updateWithRelatedEntities(String,Store):接收通过反序列化PUT请求实体构造的id和新对象Store,在新对象上设置版本(用于乐观锁定),并在事务中调用更新.

public Store updateWithRelatedEntities(String id,Store newStore) {

Store existingStore = this.get(id);

newStore.setVersion(existingStore.getVersion());

em.getTransaction().begin();

newStore = super.update(id,newStore);

em.getTransaction().commit();

return newStore;

}

> update(String,T):进行更新的通用方法.检查ids匹配并执行合并操作.

public T update(String id,T newObj) {

if (newObj == null) {

throw new EmptyPayloadException(type.getSimpleName());

}

Type superclass = getClass().getGenericSuperclass();

if (superclass instanceof Class) {

superclass = ((Class) superclass).getGenericSuperclass();

}

Class type = (Class) (((ParameterizedType) superclass).getActualTypeArguments()[0]);

T obj = em.find(type,id);

if (!newObj.getId().equals(obj.getId())) {

throw new IdMismatchException(id,newObj.getId());

}

return em.merge(newObj);

}

问题是这个调用:T obj = em.find(type,id);触发数据库中存储对象的更新,这意味着我们在触发合并时获得OptimisticLockException(因为版本现在不同).

为什么会发生这种情况?实现这一点的正确方法是什么?

我不想将属性从newStore复制到existingStore,并使用existingStore进行合并 – 我认为这将解决乐观锁定问题.

此代码未在应用程序服务器上运行,并且我没有使用JTA.

编辑:

如果我在调用update之前分离existingStore,T obj = em.find(type,id);不会触发store对象的更新,这样可以解决问题.问题仍然存在 – 为什么当实体不分离时它会触发它?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值