How to deal with dirty reads in Hibernate when accessing the same entity from multiple threads?
sobes.tech AI
Answer from AI
Dirty read in Hibernate occurs when one transaction reads data that has been modified but not yet committed by another transaction. To prevent this in multi-threaded access to the same entity, the following approaches can be used:
-
Transaction isolation level — set the isolation level to
READ_COMMITTEDor higher so that a transaction does not see uncommitted changes. -
Optimistic locking — add a version field (
@Version) to the entity; Hibernate will check the version during update, preventing data loss and ensuring consistency. -
Pessimistic locking — use
LockMode.PESSIMISTIC_WRITEorPESSIMISTIC_READto explicitly lock the entity for reading or writing at the database level. -
Proper session and transaction management — avoid long transactions and commit changes promptly.
Example of optimistic locking:
@Entity
public class Product {
@Id
private Long id;
@Version
private Integer version;
private String name;
// getters and setters
}
When updating, Hibernate will check that the version has not changed since loading, and if it has, it will throw an OptimisticLockException.
Thus, a combination of the correct isolation level and locking mechanisms helps prevent dirty reads.