Senior
Tell about locking in JPA. Which ones have you used?
sobes.tech AI
Answer from AI
In JPA, there are two main types of locking:
-
Optimistic Locking
- Used to prevent conflicts during concurrent data updates.
- Implemented with the
@Versionannotation in the entity. - When updating, the record's version is checked; if it has changed since reading, an
OptimisticLockExceptionis thrown. - Suitable for systems with low contention for data.
-
Pessimistic Locking
- Locks at the database level during read or update.
- Uses methods like
EntityManager.lock(entity, LockModeType.PESSIMISTIC_WRITE)or JPQL withLOCK. - Ensures that other transactions cannot modify or read the data until the lock is released.
- Suitable for high-concurrency scenarios where data integrity is crucial.
Example of optimistic locking:
@Entity
public class Product {
@Id
private Long id;
@Version
private Integer version;
private String name;
// getters and setters
}
When updating, JPA checks the version and throws an exception if the data has been modified by another process.
Both locking types are used depending on the consistency and performance requirements.