The Wayback Machine - https://web.archive.org/web/20240930154003/https://www.geeksforgeeks.org/hibernate-cache-eviction-with-example/
Open In App

Hibernate – Cache Eviction with Example

Last Updated : 27 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Caching in Hibernate means storing and reusing frequently used data to speed up your application. There are two kinds of caching: Session-level and SessionFactory-level. Level 1 cache is a cache that stores objects that have been queried and persist to the current session. This cache helps to reduce the number of database round trips by storing objects that are frequently accessed in the session. Level 1 cache is the default cache that is stored by default in hibernate. It is related to the hibernate session object.

Hibernate’s Level 2 caching is a built-in caching mechanism that allows you to cache data across several sessions. Level 2 cache stores data in your application’s shared cache region, which is accessible by every Hibernate session in your application. Level 2 caching can help optimize your application by reducing the number of database queries needed to load data. There are several cache providers available for Hibernate. You can use any of them, including Ehcache, Infinispan, Hazelcast, and others.

Importance of Cache Eviction

The process of cache eviction involves the deletion or replacement of data stored in a cache. This is a critical component of cache management as it guarantees that the cache remains functional and efficient. Here are some reasons why cache eviction is important:

  1. Maximizing cache space: Caches have a limited amount of space, and if the cache becomes full, new data cannot be stored. Eviction ensures that the cache is not filled with outdated or unused data, allowing space for new data.
  2. Improved cache performance: Eviction ensures that the cache only contains relevant data, increasing the cache hit rate and improving overall performance.
  3. Avoiding data staleness: Data in a cache may become stale over time, especially if it is rarely accessed. Eviction removes such data, ensuring that only fresh data is stored in the cache.
  4. Reducing cache access time: Eviction ensures that the cache only contains relevant data, which reduces the time needed to access data from the cache.
  5. Reducing cache misses: Eviction helps reduce the occurrence of cache misses, which are situations where requested data is not found in the cache, and must be retrieved from slower storage such as a disk.

Definition of Cache Eviction

When a cache gets full, it can’t store new data without getting rid of old data. That’s what cache eviction is all about. It’s the process of getting rid of or swapping out data in the cache to make room for new stuff. It’s done by using algorithms to figure out which data to get rid of. There are different policies for doing this, like LRU (Least Recently Used), LFU (Frequently Used), and RPP (Random Replacement). These policies are picked based on the type of data being stored and how often it’s accessed. The idea is to make sure the cache only has stuff that’s important and frequently accessed. That way, it’ll be more efficient and work better.

Reasons for Cache Eviction

There are several reasons for cache eviction, which are as follows:

  1. Limited cache size: Caches have a limited size, and if the cache becomes full, new data cannot be stored. Eviction ensures that the cache is not filled with outdated or unused data, making space for new data.
  2. Stale data: Data in a cache may become stale over time, especially if it is rarely accessed. Eviction removes such data, ensuring that only fresh data is stored in the cache.
  3. Access frequency: Some data may be accessed more frequently than others. Eviction algorithms can prioritize frequently accessed data and remove less frequently accessed data.
  4. Cache efficiency: Caches are designed to store frequently accessed data, and eviction ensures that the cache only contains relevant data, which improves the cache hit rate and overall performance.
  5. Cache consistency: Caches may hold copies of data that may be modified by other processes or threads. Eviction ensures that the cache holds the most recent version of the data, improving cache consistency.
  6. Dynamic data: Some data may change over time, and caching this data may not be effective. Eviction algorithms can remove data that is likely to change frequently.

Different Types of Cache Eviction

Cache eviction is the process of removing data from a cache when the cache becomes full or when the data is no longer needed. There are several different types of cache eviction algorithms used by computer systems, including:

  1. Time-Based Eviction
  2. Count-Based Eviction
  3. Query Result Eviction
  4. Cache Region Clearing

1. Time-Based Eviction

  • Time-based eviction is a cache eviction strategy that involves removing data from the cache after a certain period has elapsed since the data was last accessed or added to the cache. The idea behind this strategy is that the data in the cache may become stale or irrelevant after a certain amount of time, and it is better to remove it from the cache to make room for more relevant data.
  • Depending on your system’s requirements, you may be able to implement time-based eviction in different ways. For instance, some systems use a fixed TTL for all cache data, while others use a TTI based on how long it’s been since the last time you accessed the data.

2. Count-Based Eviction

  • Count-Based Eviction is a technique used in cache management, where items are removed from the cache based on the number of times they have been accessed. The basic idea is that items that are accessed frequently are more likely to be accessed again shortly, so they should be kept in the cache. On the other hand, items that are accessed less frequently are less likely to be accessed again, so they can be evicted to make room for more frequently accessed items.
  • Each item in your cache is associated with a counter. Every time you access an item, the counter on that item goes up. When your cache gets too full, the item that has the lowest counter will be evicted.

3. Query Result Eviction

  • Query result eviction refers to the process of removing or expiring cached query results from a database or data storage system. When a query is executed in a database, the result of that query is typically stored in a cache to improve performance. This cache can be set to expire after a certain period or when new data is added to the database.
  • When the cached query result is evicted, it is removed from the cache and the next time the same query is executed, the database will have to retrieve the data again from its primary storage location.

4. Cache Region Clearing

  • Cache region clearing refers to the process of deleting or emptying the cache data stored in a particular region of a device or system. A cache is a temporary storage area that stores frequently accessed data to improve the performance of the system. When cache data is cleared, it is removed from the cache memory, and the system needs to retrieve the data again from the source, which may take more time.
  • Cache regions can be cleared in various ways, depending on the system or device being used. For example, web browsers usually have options to clear the cache, either for specific regions or for the entire cache. Similarly, mobile devices and computers may have built-in tools for clearing the cache, or users may need to use third-party applications or software to perform the task.

Cache Eviction Strategies in Hibernate

Hibernate supports these cache eviction strategies through its second-level cache, which is a shared cache that is used to store entities and collections across multiple sessions. The second-level cache can be configured with different eviction policies for each cache region, allowing developers to optimize the caching behavior for different parts of their applications.

  1. Least Recently Used (LRU): Least Recently Unused (LRU) is an algorithm that removes data from the cache that has not been used for the longest period. LRU is based on the premise that data that has been unutilized for a long period is unlikely to be required in the future.
  2. First-In-First-Out (FIFO): First-in-first-out (FIFO) is an algorithm that prioritizes the removal of previously added data from the cache. The rationale behind this is that the longer the data has resided in the cache, the less likely it is to be required.
  3. Least Frequently Used (LFU): Least Frequently Utilized (LFU) is an algorithm that removes data from the cache based on the premise that the least frequently accessed data is unlikely to be required in the future.

Implementation of Cache Eviction in Hibernate

The following is an example code snippet that demonstrates how to implement cache eviction in Hibernate using the second-level cache.

Java




Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
  
// Enable second-level cache for the entity
sessionFactory.getCache().evictEntityRegion(User.class);
  
// Perform some database operation
User user = session.get(User.class, 1L);
user.setName("John Doe");
session.update(user);
  
// Evict the cache for the entity
sessionFactory.getCache().evictEntity(User.class, user.getId());
  
tx.commit();
session.close();


Note: You can also configure cache eviction policies using third-party libraries like Ehcache or Hazelcast. These libraries provide more advanced caching options such as eviction policies based on the time-to-live or time-to-idle.

Conclusion

  • In conclusion, cache eviction is an essential process in Hibernate’s caching mechanism that helps to maintain the accuracy and consistency of cached data. Hibernate provides a second-level cache that can be used to store entities, collections, and query results in memory. However, cached data can become stale due to database updates, and we need to remove stale data from the cache to ensure that the next retrieval of data is accurate and up-to-date.
  • Cache eviction can be implemented in Hibernate using methods like evictEntityRegion() and evictEntity() to remove cached data for specific entities. Additionally, third-party libraries like Ehcache or Hazelcast can be used to configure more advanced cache eviction policies based on time-to-live or time-to-idle.
  • Overall, understanding how to implement cache eviction in Hibernate is essential for developing high-performance applications that leverage Hibernate’s caching mechanism to improve the speed of database operations.


Previous Article
Next Article

Similar Reads

Hibernate - Create Hibernate Configuration File with the Help of Plugin
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is a java framework that is used to develop persisten
3 min read
Hibernate - Enable and Implement First and Second Level Cache
If you're a Java developer, you've probably heard of Hibernate. It's a free, open-source ORM framework that lets you map your Java objects to tables in a relational database. Basically, it makes database programming a breeze since you don't have to worry about writing SQL queries - you can just work directly with Java objects. In contrast, caching
10 min read
Hibernate - Cache Expiration
Caching in Hibernate means storing and reusing frequently used data to speed up your application. There are two kinds of caching: Session-level and SessionFactory-level. Level 1 cache is a cache that stores objects that have been queried and persist to the current session. This cache helps to reduce the number of database round trips by storing obj
9 min read
Hibernate Example using XML in Eclipse
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to perform CRUD operations, etc. In this article, let us see a Hibernate Example using XM
6 min read
Hibernate - Table Per Subclass Example using XML File
In Table Per Subclass, subclass tables are mapped to the Parent class table by primary key and foreign key relationship. In a Table per Subclass strategy : For each class of hierarchy there exist a separate table in the database.While creating the database tables foreign key relationship is required between the parent table and the child table.To p
5 min read
Hibernate Example without IDE
Hibernate is a powerful tool used to build applications that need to interact with a database. It is a Java framework that implements the ORM(Object Relational Mapping) technique. What is ORM? ORM stands for Object Relational Mapping. It is a technique that is used to make Java objects persistent by mapping them into a relational database. It simpl
3 min read
Spring ORM Example using Hibernate
Spring ORM is a module of the Java Spring framework used to implement the ORM(Object Relational Mapping) Technique. It can be integrated with various mapping and persistence frameworks like Hibernate, Oracle Toplink, iBatis, etc. for database access and manipulation. This article covers an example of the integration of the Spring ORM module with Hi
5 min read
Hibernate Native SQL Query with Example
Hibernate is a popular object-relational mapping (ORM) tool used in Java applications. It allows developers to map Java objects to database tables and perform CRUD (create, read, update, delete) operations on the database without writing SQL queries manually. Native SQL queries are useful when you need to perform complex queries that cannot be expr
7 min read
Hibernate - @Version Annotation with Example
@Version annotation is used to specify the version number for a specific entity. Version Number provided using @Version annotation is used to prevent concurrent modification to an entity. When an entity is being updated, the version number is also incremented. If another transaction tries to update the same entity with the older version number, an
3 min read
Hibernate - @Transient Annotation with Example
@Transient annotation in Hibernate is used to mark a property or field in an entity class as transient. This means that the field or property marked as transient should be excluded when the data persists in the database. Wherever an entity is mapped to a database table, by default all the non-transient fields and properties are persisted. There are
4 min read
Hibernate - @OrderBy Annotation with Example
@OrderBy annotation is used in Hibernate to specify the ordering of the elements in the collection valued property of an entity class. It is used to define the order of the elements which should be displayed. We can order the data within the entity using a specific parameter in ascending or descending order. Examples of @OrderBy AnnotationExample 1
4 min read
Spring MVC and Hibernate CRUD Example
In this article, we will be developing CRUD operations in Spring MVC and Hibernate. Hibernate is an object-relational mapping (ORM) framework. Developers use Hibernate to interact with databases using Java objects rather than SQL queries. Spring MVC is a Model-View-Controller (MVC) framework used to build web applications in Java. The Spring MVC pa
6 min read
Hibernate Example using JPA and MySQL
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is a Java framework that is used to develop persisten
4 min read
Hibernate - Annotations
Annotation in JAVA is used to represent supplemental information. As you have seen @override, @inherited, etc are an example of annotations in general Java language. For deep dive please refer to Annotations in Java. In this article, we will discuss annotations referred to hibernate. So, the motive of using a hibernate is to skip the SQL part and f
7 min read
Introduction to Hibernate Framework
Prerequisite : JDBC Need of Hibernate Framework Hibernate is used to overcome the limitations of JDBC like: JDBC code is dependent upon the Database software being used i.e. our persistence logic is dependent, because of using JDBC. Here we are inserting a record into Employee table but our query is Database software-dependent i.e. Here we are usin
4 min read
Hibernate - Bag Mapping
For a multi-national company, usually, selections are happened based on technical questions/aptitude questions. If we refer to a question, each will have a set of a minimum of 4 options i.e each question will have N solutions. So we can represent that by means of "HAS A" relationship i.e. 1 question has 4 solutions. Via Bag Mapping, in Hibernate, w
4 min read
Difference between JDBC and Hibernate in Java
Java is one of the most powerful and popular server-side languages in the current scenario. One of the main features of a server-side language is the ability to communicate with the databases. In this article, let's understand the difference between two ways of connecting to the database (i.e.) JDBC and Hibernate. Before getting into the difference
2 min read
Hibernate Lifecycle
Here we will learn about Hibernate Lifecycle or in other words, we can say that we will learn about the lifecycle of the mapped instances of the entity/object classes in hibernate. In Hibernate, we can either create a new object of an entity and store it into the database, or we can fetch the existing data of an entity from the database. These enti
4 min read
Java - JPA vs Hibernate
JPA stands for Java Persistence API (Application Programming Interface). It was initially released on 11 May 2006. It is a Java specification that gives some functionality and standard to ORM tools. It is used to examine, control, and persist data between Java objects and relational databases. It is observed as a standard technique for Object Relat
4 min read
Spring Boot - Integrating Hibernate and JPA
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Hibernate - Difference Between ORM and JDBC
Hibernate is a framework that is used to develop persistence logic that is independent of Database software. In JDBC to develop persistence logic, we deal with primitive types. Whereas Hibernate framework we use Objects to develop persistence logic that is independent of database software. ORM (Object-Relational Mapping) ORM, an abbreviation for Ob
4 min read
Hibernate - Generator Classes
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. In JDBC to develop persistence logic, we deal with primitive types. Whereas in Hibernate framework we use Objects to develop persistence logic that is independent of
5 min read
Hibernate - Create POJO Classes
POJO stands for Plain Old Java Object. In simple terms, we use POJO to make a programming model for declaring object entities. The classes are simple to use and do not have any restrictions as compared to Java Beans. To read about POJO classes and Java Bean refer to the following article - POJO classes and Java Bean POJO is handier as its best in r
3 min read
Hibernate - One-to-One Mapping
Prerequisite: Basic knowledge of hibernate framework, Knowledge about databases, Java Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to
15 min read
Hibernate - SQL Dialects
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. An ORM(Object-relational mapping) framework simplifies data creation, data manipulation, and data access. It is a programming technique that maps the object to the d
3 min read
Hibernate - Web Application
A web application with hibernate is easier. A JSP page is the best way to get user inputs. Those inputs are passed to the servlet and finally, it is inserted into the database by using hibernate. Here JSP page is used for the presentation logic. Servlet class is meant for the controller layer. DAO class is meant for database access codes. Tools and
9 min read
Hibernate - Table Per Concrete Class using XML File
Hibernate is capable of storing the inherited properties of an object along with its new properties in its database when an object is saved in the database. In Hibernate, inheritance between POJO classes is applied when multiple POJO classes of a module contain some common properties. In a real-time application, POJO classes of Hibernate are design
5 min read
Hibernate - Table Per Subclass using Annotation
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. An ORM(Object-relational mapping) framework simplifies data creation, data manipulation, and data access. It is a programming technique that maps the object to the d
6 min read
Hibernate - Table Per Hierarchy using XML File
Hibernate is capable of storing the inherited properties of an object along with its new properties in its database when an object is saved in the database. In Hibernate, inheritance between POJO classes is applied when multiple POJO classes of a module contain some common properties. In a real-time application, POJO classes of Hibernate are design
6 min read
Hibernate - Criteria Queries
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to perform CRUD operations, etc. To get the data available in RDBMS tables, Hibernate fol
12 min read
Article Tags :
Practice Tags :