Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

前端 未结 17 1888
别跟我提以往
别跟我提以往 2020-12-02 16:36

I have a java project that runs on a webserver. I always hit this exception.

I read some documentation, and found that pessimistic locking (or optimistic, but I read

17条回答
  •  生来不讨喜
    2020-12-02 17:08

    I know this is an old question, but some of us are still hitting it and look at sky wandering how. Here is one kind of issue that I faced,

    We have a queue manager that polls data and give to handlers for processing. To avoid picking up the same events again, the queue manger locks the record in database with a LOCKED state.

       void poll() {
            record = dao.getLockedEntity();
            queue(record);
         }
    

    this method wasn't transactional but dao.getLockedEntity() was transactional with 'REQUIRED'.

    All good and on the road, after few months in production, it failed with optimistic locking exception,

    After lots of debugging and checking in details we could find out that some one has changed the code like this,

    @Transactional(propagation=Propagation.REQUIRED, readOnly=false)
    void poll() {
            record = dao.getLockedEntity();
            queue(record);              
         }
    

    So the record was queued even before the transaction in dao.getLockedEntity() get committed (it uses the same transaction of poll method) and the object was changed underneath by the handlers (different threads) by the time the poll() method transaction get comitted.

    We fixed the issue and it looks good now.

    I thought of sharing it, because optimistic lock exception can be confusing and are difficult to debug. Some one might get benefited from my experience.

    Regards Lyju

提交回复
热议问题