Hibernate L1 Cache - DevDummy

Latest

Guildes | Concepts | Techniques

Wednesday, October 17, 2018

Hibernate L1 Cache



Hibernate Level 1 Cache

Hibernate contains a very sophisticated caching mechanism which increases the  performance of the data fetching. Level 1 caching mechanism is the simplest and most straightforward solution provided.

Hibernate L1 cache is enabled by default and there is no way to disable it. More importantly, it is bound with each hibernate session scope. It means all the related entities for the specific session are stored within the session.

Hibernate L1 cache works only for find method on the entity manager or traversing on linked entities, but not for any queries triggered for find.

Example:

entityManager.find(book.class, 1L)

That means when the entities are fetched using the entitymanager, the results are stored in the hibernate L1 cache and fetched from the cache instead from the database which is a costly operation.

However this can lead to problematic behaviours as well,
  • Data contains in the cache is session scoped, hence can be obsolete
  • In bulk fetched or batch fetches, cache can be overflow and make negative impacts on performance of the application.
It is always possible to control the content of the Hibernate L1 cache. detach() method can be used to remove individual cached entities and clear() can be used to remove all the cached entities.

Above two methods remove cached entities not persisting any updates in the database unless the session is flushed.

...



No comments:

Post a Comment