Hibernate: Story of Caching
Caching is important for performance, so we take a look at how it works with an ORM like Hibernate.
Join the DZone community and get the full member experience.Join For Free
in this article, we are going to talk about caching in hibernate.
hibernate is an orm framework for java. it is a framework for mapping an object-oriented model to an relational model. hibernate is concerned with data persistence as it applies to relational databases (via jdbc). it performs powerful object-relational mapping and query databases using hql and sql. it can cut down a lot of complexity and, thus, defects as well from your application, which may otherwise find a way to exist. we can also say it is a boon for developers with limited knowledge of sql.
caching is a mechanism to store data in a buffer memory (also known as cache) so that future request can be served faster. it helps in reducing the number of interaction to the database and enhance the performance of a system.
why is catching important?
- enhance the performance of database applications.
- reduces traffic between your application and the database
- access database if data is not available in the cache.
types of cache
in this blog, we will focus on first-level cache. we will talk about second level and query cache in the next blog.
first level cache is a session cache. it is a session-scoped cache, which ensures that each entity instance is loaded only once in the persistent context. it is enabled by default and there is no way to disable it. as it is a session-scoped cache, all concurrent session work in isolation. once the session is closed, its first-level cache is terminated as well.
whenever an application tries to load an entity it searched in the first-level cache, if it is not able to find a first-level cache, it hits the database and executes the query and stores it in the first-level cache and returns the result to the application.
some important methods to control the first-level cache
the first-level cache is the default cache in hibernate, and there is no way to disable it. but, hibernate provides some methods to control it.
it removes an object from the session cache. after removing the object from the session, any change to object will not be persisted.
when this method called, the first-level cache for that session is cleared, as well as all the objects from the cache.
this method can be used to check that the given instance is associated with this session.
in the next blog, we will look at the second-level cache. stay tuned!
Published at DZone with permission of Nitin Ranjan, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.