Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jpa creating new entity while deleting old one that has the same primary key value

consider a case when user delete entity A that has primary key value x then insert another entity with same primary key value x in the same transaction. then commit the transaction. A has a version field . the version field of the newly created entity is zero thus
an optimistic lock exception occurred stating that entity A with primary key x might have been updated or deleted when transaction commited. i tried unit of work dot should perform delete first but the same result occur. is there a way to tell jpa that this is a new entity.

like image 280
bob-cac Avatar asked Mar 18 '23 04:03

bob-cac


1 Answers

That is a rare case you might wanna try flushing your deletion first (which will also detach the affected entity), before persisting the new entity in the same transaction. Otherwise you are hoping that your persistence provider will tolerate the coexistence of two different entities with the exact same identity in the persistence context. None of the persistence providers I know, will ever allow this situation. As esej points out above, any provider will regard each entity instance with the same id as representing the very same entity and thus allow only a single reference to exist at a given time in the persistence context. In your special case the persist operation of the new entity causes the replacement of the entity to be deleted in the persistence context, even before the delete operation was committed and actually took place. Thus at commit time the only thing the provider tries to do is updating the database with your new entity. No surprise an optimistic lock exception is thrown.

like image 68
Lars Avatar answered Apr 25 '23 02:04

Lars