JPA: locking when performing an indirect insertion

前端 未结 2 1731
梦谈多话
梦谈多话 2020-12-11 23:03

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

相关标签:
2条回答
  • 2020-12-11 23:26

    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.

    0 讨论(0)
  • 2020-12-11 23:26

    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 Prescription entity as its corresponding database row is not changed when a new Dose is added to it. This stems from the fact that the Dose is the owning side of the relationship between itself and its Prescription. In the database, the row that represents the Dose will have a foreign key pointing to the Prescription, but the row that represents the Prescription will have no pointers to any of its Doses. The problem is remedied by guarding the Prescription with an optimistic write lock that forces an update to the Prescription’s row (to be specific: its version field) when a new Dose is inserted.

    0 讨论(0)
提交回复
热议问题