Home > Software design >  Spring JPA transactional to avoid concurrency read / update
Spring JPA transactional to avoid concurrency read / update

Time:08-31

Using Spring boot and JPA/hibernate , I'm looking for a solution to avoid a table record being read by another process while I'm reading then updating an entity. Isolation levels Dirty read, Nonrepeatable read and Phantom read are not so clear for me. I mean if process #1 starts a read/update i don't want a process #2 to be able to read the old value (before updated by #1) and then update the structure with wrong values.

CodePudding user response:

isolation levels all prevent reading changes in different levels of strictness:

  • Dirty Read -> reading not yet committed changes
  • Nonrepeatable read -> quering the same row second time finds data changes
  • Phantom read -> like previous but instead of data changes, it finds more data added (more here)

Serializable level, being the strictest, would prevent reading any changes yet, essentially resulting in sequential processing in DB (no concurrency) and would probably solve your problem

What you are looking for, if I understood correctly, is to block second process from doing any work until row update is complete - that is called row locking, and can be controlled directly as well (without setting serializable isolation)

See more about row locking with Spring JPA here: https://www.baeldung.com/java-jpa-transaction-locks

If it wasn't different process (different program) but just a different thread within the same Java program a simple synchronized would do the trick as well

  • Related