Home  >  Article  >  Java  >  How does Hibernate second level cache work?

How does Hibernate second level cache work?

PHPz
PHPzforward
2023-09-14 19:45:021209browse

How does Hibernate second level cache work?

Caching helps reduce database network calls when executing queries.

Level 1 cache and session link. It is implemented implicitly. Level 1 cache exists until the session object exists. Once the session object is terminated/closed there will be There are no cached objects. Second level cache works for multiple session objects. it is linked with session factory. Second level cache objects are available to all sessions Single session factory. These cached objects will be terminated when a specific session occurs The factory is closed.

Implementing second-level cache

We need to add the following dependencies to use the second level cache.

<!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
<dependency>
   <groupId>net.sf.ehcache</groupId>
   <artifactId>ehcache</artifactId>
   <version>2.10.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-ehcache -->
<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-ehcache</artifactId>
   <version>5.4.32.Final</version>
</dependency>

Note- The hibernate ehcache version number must be the same as the hibernate version number.

Now, we need to add the hibernate configuration file, which will enable hibernate to connect to Provided database and uses second level cache.

<!DOCTYPE hibernate-configuration PUBLIC
   "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
   "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
   <session-factory>
      <!-- JDBC Database connection settings -->
      <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
      <property name="connection.url">jdbc:mysql://localhost:3306/demo?useSSL=false</property>
      <property name="connection.username">root</property>
      <property name="connection.password">root</property>
      <!-- JDBC connection pool settings ... using built-in test pool -->
      <property name="connection.pool_size">4</property>
      <!-- Echo the SQL to stdout -->
      <property name="show_sql">true</property>
      //caching properties
      <property name="cache.use_second_level_cache">true</property>
      <property name="cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
      <!-- Select our SQL dialect -->
      <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
      <!-- Drop and re-create the database schema on startup -->
      <property name="hbm2ddl.auto">create-drop</property>
      <!-- name of annotated entity class -->
      <mapping class="academy.company.Parent"/>
   </session-factory>
</hibernate-configuration>

Example

By default, all entities in java are not cached. So, to enable caching of entities, we use @Cacheable and @Cache annotations -

in entity class Parent
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;

@Entity
@Table( name = " Employee")
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class Parent {
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   Long id;
   @Column(name = "first_name")
   String firstName;
   @Column(name = "last_name")
   String lastName;
}
Now, let’s check whether second level cache works:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Main {
   public static void main(String[] args) {
      SessionFactory sessionFactory = new Configuration()
         .configure("academy/company/hibernate.cfg.xml")
         .buildSessionFactory();
      Session session1 = sessionFactory.openSession();
      Parent parent1 = session1.get(Parent.class, 4);
      System.out.println(parent1.id + " " + parent1.firstName + " " + parent1.lastName);
      session1.close();
      
      Session session2 = sessionFactory.openSession();
      Parent parent2 = session2.get(Parent.class, 4);
      System.out.println(parent2.id + " " + parent2.firstName + " " + parent2.lastName);
      session2.close();
   }
}

Output

Hibernate: select parent0.id as id1, parent0.first_name as first_name1, parent0.last_name as last_name1 from Parent parent0 where parent0.id=?
1 Subash Chopra
1 Subash Chopra

From the console we can clearly see that hibernate only executed one query during session1. Now, when session2 accesses the same query, it doesn't make a network call to the database to execute it. Instead, since we are using the second level cache, it will get the cache object from session1.

The above is the detailed content of How does Hibernate second level cache work?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete