Merge detached JPA entity with @version field
I have a JPA entity class with a @Version field for optimistic locking. I need to merge()
a detached entity instance that has its version field uninitialized over an existing entity instance in the persistence context. When doing this the managed instance has its version field overwritten which leads to an OptimisticLockException later on.
I could manually copy contents of the version field from the managed to the detached entity before merging but I find this a bit awkward. Is there a better option or best practice to handle this scenario?
Doing merge is not going to work if you have the version field uninitialized. It has to be there. The JPA provider will have to compare the version field of the entity you are trying to merge with the version that is in the database. If entity version is older than what is in the database, then it will have to throw an exception.
What you can do instead of doing a merge, is to use update via JPA query:
Query q = em.createQuery("UPDATE MyEntity me SET me.versionField = me.versionField + 1....");
q.executeUpdate();
You can set the other fields of your entity in this query, but what's important is you have to explicitly increment the value of the version field. The version field is not automatically incremented on updates via query.
链接地址: http://www.djcxy.com/p/89600.html