Part 2, Chapter 13
Every new chapter of my book is released right after it’s being completed, so the reader doesn’t have to wait for the whole part to be finished to get access to new material.
Table of content
This chapter explains the inner-workings of the Hibernate Persistence Context implementation.
13. Flushing 13.1 Flush modes 13.2 Events and the action queue 13.2.1 Flush operation order 13.3 Dirty Checking 13.3.1 The default dirty checking mechanism 220.127.116.11 Controlling the Persistence Context size 13.3.2 Bytecode enhancement
As explained in the write-based optimizations section, the Persistence Context acts as a transactional write-behind cache. The Hibernate Session is commonly referred to as the first-level cache since every managed entity is stored in a Map, and, once an entity is loaded, any successive request serves it from the cache, therefore avoiding a database roundtrip.
However, aside from caching entities, the Persistence Context acts as an entity state transition buffer.
Like any write-behind cache, the Persistence Context requires flushing in order to synchronize the in-memory persistent state with the underlying database. At flush time, Hibernate can detect if a managed entity has changed since it was loaded and trigger a table row update. This process is called dirty checking, and it greatly simplifies data access layer operations.
However, having an intermediate write-behind cache is not without challenges and the Persistence Context can be subject to data inconsistencies. Since efficiency is meaningless if effectiveness is being compromised, this chapter aims to analyze the inner-workings of the flushing mechanism, so the application developer knows how to optimize it without affecting data consistency.