I am writing a piece of software that tracks medication usage. I am using JPA to interact with the database. My model consists of two entities: a Prescription a
It Seems right.
However, I'll suggest to test it first... the more simple way to do this, is through debugging ... using your preferred IDE, set a debug point after the sentence:
entityMgr.lock(p, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
Later, try to invoke your addDose(prescriptionId) from two different clients, supplying the same prescriptionID ... and let one client finish first and see what happen with the another one.
This answer helped me understand the OPTIMISTIC_WRITE_LOCK better and convinced me that my implementation is correct.
A more elaborate explanation follows (quotation added as it appears in a report authored by myself):
While EJB transactions may help prevent concurrent changes to the persisted state of an entity, they are insufficient in this case. This is because they are unable to detect the change to the
Prescriptionentity as its corresponding database row is not changed when a newDoseis added to it. This stems from the fact that theDoseis the owning side of the relationship between itself and itsPrescription. In the database, the row that represents theDosewill have a foreign key pointing to thePrescription, but the row that represents thePrescriptionwill have no pointers to any of itsDoses. The problem is remedied by guarding thePrescriptionwith an optimistic write lock that forces an update to thePrescription’s row (to be specific: its version field) when a newDoseis inserted.