how dirty read works in hibernate

9.1k views Asked by At

According to Manning's Java Persistence with Hibernate:

dirty read occurs if a one transaction reads changes made by another transaction that has not yet been committed. This is dangerous, because the changes made by the other transaction may later be rolled back, and invalid data may be written by the first transaction.

if a record is retrieved from database , there is a corresponding object been created in the persistent state and whatever changes are made , are first written on the persistent object , hence making it dirty.

Now my question is if some other transaction is reading the same record , then whether it will read the record from the persistent state ie the first level cache(which is dirty at the moment) or it will retrieve the record from database.

1

There are 1 answers

1
Shailendra On

First level cache is not shared across transactions. Except in case of Extended persistence contexts the most common pattern used is that each transaction is associated with a single session/persistence-context and has its own first level cache which is being tracked only for that transaction.

Actually "dirty-read" is a property of database transaction and not Hibernate in general. When one transaction reads changes made by another transaction that has not yet been committed it is called dirty read. It is dangerous and unusual to use this type of transaction because the read data might get rolled back.

whatever changes are made , are first written on the persistant object , hence making it dirty.

What you are saying in the above line is that there have been changes made to object (but changes are not yet sent to database because ORM's like Hibernate delay the flushing the sql till the end of transaction). So the object after the change is now dirty but the same cannot be said about the transaction as no insert/update/delete have been sent to database.Talking about Hibernate - the reason it is considered "dirty" from application perspective is that the object representation of data read by hibernate can be changed by using setters and so the object or data becomes "dirty" which needs to be flushed to database at the end of transaction or the application may actually decide not to commit. The primary job of Hibernate is to keep track of this changed ("dirty") state and at the end of transaction generate appropriate insert/update/delete. So this dirtiness is difference between state initially read and state after changes made if any within the same transaction.