Let us understand how jpa caching method is divided in different layers.
Although JPA Caching includes two levels, i.e. Persistence context and shared level, roughly an application can have different levels. Let us understand the diagram which I’ve drawn quite similar to the one in Apress : Mastering Java Persistence API 2.0 book.
Though application level cannot be considered as a real level of JPA caching, we can write some applications such that they hold references to jpa entities. These entities can become stale as they will be placed in application level.
Persistence Context level:
This jpa caching level is the first real caching level. It is the first level from which a persistence provider can retrieve entities from memory and within transaction boundaries. Cached entities are not available when a transaction completes. In case of extended persistence contexts, the cache is unavailable after transaction is closed.
Shared Cache level:
JPA Caching in EntityManagerFactory is the real second level cache JPA provides. Cached entities from EntityManagerFactory are shared across all entitymanagers and hence the name shared cache.
JDBC Cache level:
This isn’t also a real JPA caching level. JDBC drivers can cache connections and statements. Some drivers can track tables and columns.
Let us understand what happens when a find operation is performed for entity.
Vehicle vehicle = em.find(Vehicle.class,1);
- Application from which find method is called looks in its local cache for vehicle with id = 1. It if doesn’t find, it issues the call on entity manager.
- EntityManager checks for vehicle in its persistence context. This is the first real jpa caching level. If it is available in persistence context, it is returned otherwise, entity is searched in shared cache.
- If the entity is present in shared cache, an instance is created and put in persistence context level cache.
- If entity is not present in shared cache also, sql query is generated to select the entity row from database. The query result is used to create an object and it is passed back to shared cache.
- This newly created instance is put into shared cache and a new copy of the same instance is put into persistence context level cache where it becomes managed by entity manager.
References for further study :