Java – optimizationlockexception when JPA merge() is used

I have a rest app where a resource can be updated Here are two ways to accomplish this task:

> updateWithRelatedEntities (String, Store): receive ID and new object Store constructed by anti serialization PUT request entity, set the version on the new object (for optimistic locking), and call the update in the transaction.

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): a general method for updating Check the IDS match and perform the merge operation

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<T> type = (Class<T>) (((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);
}

The problem is this call: t obj = em.find (type, ID); Trigger the update of stored objects in the database, which means that we get the optimizationlockexception when triggering the merge (because the version is different now)

Why did this happen? What is the right way to achieve this?

I don't want to copy properties from newstore to existingstore and merge them using existingstore - I think this will solve the optimistic locking problem

This code is not running on the application server, and I am not using JTA

Edit: if I separate existingstore before calling update, t obj = em.find (type, ID); The update of the store object will not be triggered, which can solve the problem The question remains – why does it trigger an entity when it does not detach?

Solution

I can't see your entity from the code you added, but I believe you've lost some key points with optimistic locking > @ version annotation version field

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>