Table of Contents
Implementing second-level cache
Example
Output
Home Java javaTutorial How does Hibernate second level cache work?

How does Hibernate second level cache work?

Sep 14, 2023 pm 07:45 PM
Work hibernate L2 cache

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.

1

2

3

4

5

6

7

8

9

10

11

12

<!-- 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>

Copy after login

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

<!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>

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

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();

   }

}

Copy after login

Output

1

2

3

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

Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the first-level cache and second-level cache of mybatis? What are the first-level cache and second-level cache of mybatis? Jan 15, 2024 pm 01:44 PM

Mybatis's first-level cache is enabled by default and is at the SqlSession level. This means that multiple queries in the same SqlSession will take advantage of this level of caching. The first-level cache mainly stores query results. When executing a query operation, MyBatis will store the mapping relationship between the mapping statement and the query result, as well as the query result data in the cache. The second-level cache of mybatis is different from the first-level cache. The second-level cache is shared throughout the application, unlike the first-level cache in each SqlSession and so on.

Analyze the caching mechanism of MyBatis: compare the characteristics and usage of first-level cache and second-level cache Analyze the caching mechanism of MyBatis: compare the characteristics and usage of first-level cache and second-level cache Feb 25, 2024 pm 12:30 PM

Analysis of MyBatis' caching mechanism: The difference and application of first-level cache and second-level cache In the MyBatis framework, caching is a very important feature that can effectively improve the performance of database operations. Among them, first-level cache and second-level cache are two commonly used caching mechanisms in MyBatis. This article will analyze the differences and applications of first-level cache and second-level cache in detail, and provide specific code examples to illustrate. 1. Level 1 Cache Level 1 cache is also called local cache. It is enabled by default and cannot be turned off. The first level cache is SqlSes

How to integrate Hibernate in SpringBoot project How to integrate Hibernate in SpringBoot project May 18, 2023 am 09:49 AM

Integrating Hibernate in SpringBoot Project Preface Hibernate is a popular ORM (Object Relational Mapping) framework that can map Java objects to database tables to facilitate persistence operations. In the SpringBoot project, integrating Hibernate can help us perform database operations more easily. This article will introduce how to integrate Hibernate in the SpringBoot project and provide corresponding examples. 1.Introduce dependenciesIntroduce the following dependencies in the pom.xml file: org.springframework.bootspring-boot-starter-data-jpam

Java Errors: Hibernate Errors, How to Handle and Avoid Java Errors: Hibernate Errors, How to Handle and Avoid Jun 25, 2023 am 09:09 AM

Java is an object-oriented programming language that is widely used in the field of software development. Hibernate is a popular Java persistence framework that provides a simple and efficient way to manage the persistence of Java objects. However, Hibernate errors are often encountered during the development process, and these errors may cause the program to terminate abnormally or become unstable. How to handle and avoid Hibernate errors has become a skill that Java developers must master. This article will introduce some common Hib

What jobs can I apply for in 2023 with my Java skills? What jobs can I apply for in 2023 with my Java skills? Sep 21, 2023 am 11:41 AM

When we talk about programming languages ​​and jobs, one programming language that comes to our mind is Java. Most companies around the world use Java. It's popular and there are many job opportunities. If you want to get a job with the help of Java skills in 2023, then this is good for you as Java skills can get you a job quickly. Plus, it can quickly advance your career. There is no magic trick that will make you find a job quickly. But your skills are like magic to you. Choose a job that satisfies you and a good environment that can greatly enhance your career. If you are a newbie and have experience, Java also provides you with a good job. Many companies use Java as the main program for their development. it

What are the differences between hibernate and mybatis What are the differences between hibernate and mybatis Jan 03, 2024 pm 03:35 PM

The differences between hibernate and mybatis: 1. Implementation method; 2. Performance; 3. Comparison of object management; 4. Caching mechanism. Detailed introduction: 1. Implementation method, Hibernate is a complete object/relational mapping solution that maps objects to database tables, while MyBatis requires developers to manually write SQL statements and ResultMap; 2. Performance, Hibernate is possible in terms of development speed Faster than MyBatis because Hibernate simplifies the DAO layer and so on.

Analysis of front-end engineer responsibilities: What is the main job? Analysis of front-end engineer responsibilities: What is the main job? Mar 25, 2024 pm 05:09 PM

Analysis of front-end engineer responsibilities: What is the main job? With the rapid development of the Internet, front-end engineers play a very important professional role, playing a vital role as a bridge between users and website applications. So, what do front-end engineers mainly do? This article will analyze the responsibilities of front-end engineers, let us find out. 1. Basic responsibilities of front-end engineers Website development and maintenance: Front-end engineers are responsible for the front-end development of the website, including writing the website’s HTML, CSS and JavaScr

What is the mapping method of one-to-many and many-to-many relationships in Java Hibernate What is the mapping method of one-to-many and many-to-many relationships in Java Hibernate May 27, 2023 pm 05:06 PM

Hibernate's one-to-many and many-to-many Hibernate is an excellent ORM framework that simplifies data access between Java applications and relational databases. In Hibernate, we can use one-to-many and many-to-many relationships to handle complex data models. Hibernate's one-to-many In Hibernate, a one-to-many relationship means that one entity class corresponds to multiple other entity classes. For example, an order can correspond to multiple order items (OrderItem), and a user (User) can correspond to multiple orders (Order). To implement a one-to-many relationship in Hibernate, you need to define a collection attribute in the entity class to store

See all articles