In the context of REST APIs, databases, and Spring Boot, pessimistic locking and optimistic locking are two ways to manage data updates. This ensures data consistency but can cause delays.

Pessimistic Locking : Spring Boot allows the use of pessimistic locks through JPA’s @Lock annotation or by specifying lock options in a query.

How it works: When a record is read with a pessimistic lock, it is locked for others, preventing any other transaction from modifying it until the lock is released. This avoids conflicts but can reduce performance.

Example:

@Lock(LockModeType.PESSIMISTIC_WRITE)

@Query("SELECT p FROM Product p WHERE p.id = :id") Product findProductForUpdate(@Param("id") Long id);

Optimistic locking doesn’t lock the record initially. Instead, it checks if the data has changed before updating. If another user has modified the data, the operation fails, and the user must retry. This method is faster and more efficient but requires careful error handling.

Versioning: Spring Boot uses a version field in the entity, typically annotated with @Version. Each time the entity is updated, the version number increases.

How it works: When an update is made, the version number in the database is checked. If it matches the version in the entity, the update proceeds. If another transaction has modified the entity (and thus changed the version), an OptimisticLockException is thrown, signaling a conflict.

Example:

@Entity

public class Product {

@Id

private Long id;

@Version private int version; // other fields, getters, and setters

}

Hinterlasse einen Kommentar

I’m Iman

Mein Name ist Iman Dabbaghi. Ich arbeite als Senior Software Engineer in der Schweiz. Außerdem interessiere ich mich sehr für gewaltfreie Kommunikation, Bachata-Tanz und Musik sowie fürs die Persönlichkeitsentwicklung.

Ich habe einen Masterabschluss in Informatik von der Universität Freiburg in Deutschland, bin Spring/Java Certified Professional (OCP), Certified Professional for Software Architecture (CPSA-F) und ein lebenslanger Lernender 🎓.

EN:

My name is Iman Dabbaghi. I work as a Senior Software Engineer in Switzerland. I am also very interessted in nonviolent communication, Bachata dance and music and also for personal development.

I hold a masters degree in computer science from the university of Freiburg in Germany, am a Spring / Java Certified Professional (OCP), Certified Software Architecture (CPSA-F) and Life Long Learner🎓

Let’s connect