Search code examples
javahibernatejakarta-eejpatransactions

How to prevent Lost Updates in a Java application which uses Hibernate?


How can I prevent the lost update issue in my Java web-start application? The scenario is if 2 users are accessing the same record and one person just make some modification and updates the DB. Other user still have the old data and without knowing that the first user had changed the data he makes some modification and updates the DB. This result to the lost update of first user.

I need to make sure that before saving the application need to compare the record with DB and if there is a change found the the user needs to be informed and some way I need to make sure the user sees the change after wards the current user can apply his change and submit again to the DB.

Following is the details of my Java web start application:

  • Application uses Java web-start technology which communicates with the Servlets running on Tomcat7.
  • DB is SQL Server 2012.
  • Server Machine: Windows 64 bit 2008 R2 Enterprise Server.
  • Java 7 update 25 64 bit
  • Hibernate version - 3.0

Is there any way to implement this?

Kindly advice.

Thanks in advance


Solution

  • This sounds like a classic case for an optimistic strategy e.g.

    Optimistic concurrency control (OCC) is a concurrency control method for relational database management systems that assumes that multiple transactions can complete without affecting each other, and that therefore transactions can proceed without locking the data resources that they affect. Before committing, each transaction verifies that no other transaction has modified its data. If the check reveals conflicting modifications, the committing transaction rolls back

    Perhaps maintaining record version numbers.

    e.g. each record would maintain a record version number. When a client receives the client, it would receive the version number too. Upon modification the server compares the record number with that in the database, and if not changed, then a new record is written with an incremented version number.

    A second client would then come in with the same record number (i.e. the record is being updated by both clients). This time the server would recognise that the version number has changed, and reject the update.

    Note that various implementation options exist. The database can implement this using record numbers or timestamps. The database can maintain a history of edits, or simply the latest version of the record.