Home Java javaTutorial Introduction to hibernate caching mechanism

Introduction to hibernate caching mechanism

Jul 17, 2017 pm 05:52 PM
hibernate mechanism cache

hibernate first-level cache

1.Hibernate first-level cache is also called "Session cache" and "session-level cache".

2. When querying an entity from the database through Session, the entity will be stored in the memory. The next time you query the same entity, it will no longer be obtained from the database, but from the memory. This is cache

3. The life cycle of the first-level cache is the same as that of the Session. When the Session is destroyed, it is also destroyed.

4. The applicable range of data in the first-level cache is within the current session.

why (Why use Hibernate cache?)

Hibernate is a persistence layer framework that often accesses physical databases .

In order to reduce the frequency of application access to physical data sources, thereby improving the running performance of the application.

The data in the cache is a copy of the data in the physical data source. The application reads and writes data from the cache at runtime. At a specific moment or event, the data in the cache and the physical data source will be synchronized


#what( What is the principle of Hibernate cache? ) Hibernate cache includes two categories: Hibernate first-level cache and Hibernate second-level cache.

1.Hibernate first-level cache is also called "Session cache".

Session built-in cannot be unloaded, and the Session cache is a transaction-scope cache (the life cycle of the Session object usually corresponds to a database transaction or an application transaction).

In the first-level cache, each instance of the persistent class has a unique OID.

2.Hibernate second-level cache is also called "SessionFactory cache".

Since the life cycle of the SessionFactory object corresponds to the entire process of the application, the Hibernate second-level cache is a process-wide or cluster-wide cache. Concurrency problems may occur, so an appropriate concurrent access strategy needs to be adopted. Policies provide transaction isolation levels for cached data.

The second level cache is optional and is a configurable plug-in. SessionFactory will not enable this plug-in by default.

Hibernate provides the org.hibernate.cache.CacheProvider interface, which acts as an adapter between the cache plug-in and Hibernate.

What kind of data is suitable to be stored in the second level cache?

1) Data that is rarely modified
2) Data that is not very important, occasional concurrent data is allowed
3) Data that will not be accessed concurrently
4) Constant data
Data that is not suitable for storage in the second level cache?
1) Data that is frequently modified
2) Data that is never allowed to be accessed concurrently, such as financial data, is never allowed to be accessed concurrently
3) Data shared with other applications.


API for managing the first-level cache

1.evict(), used to clear an object from the Session’s first-level cache.

2.clear(), used to clear all objects in the first-level cache.

Qurey.list() and Qurey.iterate()

1.Qurey.list() query data , will not search from the first-level cache, directly send the SQL statement to the database, and retain the object returned by the query in the cache.

2.Qurey.iterate() does not search from the first-level cache, but directly sends sql to the database to query the id. When other attributes of the object need to be used, the object is first searched for in the cache according to the id. If there is no Then send a sql query to the database, so using this method alone to query will cause an N+1 problem (that is, sending N+1 statements to the database to query the information of N objects)

3. If this requirement exists: The same object needs to be accessed in two different sessions. Two sql statements or more need to be sent through Qurey.list(). In order to avoid setting up a second-level cache, Query.list() in the first session , in the second session, directly obtain it from the second-level cache through Qurey.iterate() iteration

hibernate second-level cache (SessionFactory cache)

1. Add the configuration in hibernate.cfg.xml

        <!-- 开启二级缓存 --><property name="hibernate.cache.use_second_level_cache">true</property><!-- 二级缓存的提供类 在hibernate4.0版本以后我们都是配置这个属性来指定二级缓存的提供类--><property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property><!-- 二级缓存配置文件的位置 --><property name="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</property>
Copy after login
2. For details about the configuration of ehcache.xml, see


3. Configure the entity through annotations, and add @Cache(usage=CacheConcurrencyStrategy.READ_ONLY) in front of the class

Common CacheConcurrencyStrategy attribute values ​​​​are READ_ONLY (the table data corresponding to the entity is only read and then cached) and READ-WIRTE (table data can be read or updated)

4, be sure to note: hibernate's second-level cache must be the entire object. If only some attributes of the object are queried, then the object will not Cached

Query cache (SessionFactory level cache)

1. Continue based on the above second-level cache Configuration

2. Add configuration

  <property name="hibernate.cache.use_query_cache">true</property>
Copy after login
in hibernate.cfg.xml

2. Add @Cacheable to the entity annotation

3. Call the setCacheable(true) method after the hql statement

4. Only when the HQL query statement is exactly the same, even the parameters The settings must be the same, and the query cache is effective at this time

hibernate's three states (transient (transient state), persistent (persistent state) and detached ( Offline))


The above is the detailed content of Introduction to hibernate caching mechanism. 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)

Where are video files stored in browser cache? Where are video files stored in browser cache? Feb 19, 2024 pm 05:09 PM

Which folder does the browser cache the video in? When we use the Internet browser every day, we often watch various online videos, such as watching music videos on YouTube or watching movies on Netflix. These videos will be cached by the browser during the loading process so that they can be loaded quickly when played again in the future. So the question is, in which folder are these cached videos actually stored? Different browsers store cached video folders in different locations. Below we will introduce several common browsers and their

How to view and refresh dns cache in Linux How to view and refresh dns cache in Linux Mar 07, 2024 am 08:43 AM

DNS (DomainNameSystem) is a system used on the Internet to convert domain names into corresponding IP addresses. In Linux systems, DNS caching is a mechanism that stores the mapping relationship between domain names and IP addresses locally, which can increase the speed of domain name resolution and reduce the burden on the DNS server. DNS caching allows the system to quickly retrieve the IP address when subsequently accessing the same domain name without having to issue a query request to the DNS server each time, thereby improving network performance and efficiency. This article will discuss with you how to view and refresh the DNS cache on Linux, as well as related details and sample code. Importance of DNS Caching In Linux systems, DNS caching plays a key role. its existence

Will HTML files be cached? Will HTML files be cached? Feb 19, 2024 pm 01:51 PM

Title: Caching mechanism and code examples of HTML files Introduction: When writing web pages, we often encounter browser cache problems. This article will introduce the caching mechanism of HTML files in detail and provide some specific code examples to help readers better understand and apply this mechanism. 1. Browser caching principle In the browser, whenever a web page is accessed, the browser will first check whether there is a copy of the web page in the cache. If there is, the web page content is obtained directly from the cache. This is the basic principle of browser caching. Benefits of browser caching mechanism

Advanced Usage of PHP APCu: Unlocking the Hidden Power Advanced Usage of PHP APCu: Unlocking the Hidden Power Mar 01, 2024 pm 09:10 PM

PHPAPCu (replacement of php cache) is an opcode cache and data cache module that accelerates PHP applications. Understanding its advanced features is crucial to utilizing its full potential. 1. Batch operation: APCu provides a batch operation method that can process a large number of key-value pairs at the same time. This is useful for large-scale cache clearing or updates. //Get cache keys in batches $values=apcu_fetch(["key1","key2","key3"]); //Clear cache keys in batches apcu_delete(["key1","key2","key3"]);2 .Set cache expiration time: APCu allows you to set an expiration time for cache items so that they automatically expire after a specified time.

How to save video files from browser cache to local How to save video files from browser cache to local Feb 23, 2024 pm 06:45 PM

How to Export Browser Cache Videos With the rapid development of the Internet, videos have become an indispensable part of people's daily lives. When browsing the web, we often encounter video content that we want to save or share, but sometimes we cannot find the source of the video files because they may only exist in the browser's cache. So, how do you export videos from your browser cache? This article will introduce you to several common methods. First, we need to clarify a concept, namely browser cache. The browser cache is used by the browser to improve user experience.

Caching mechanism and application practice in PHP development Caching mechanism and application practice in PHP development May 09, 2024 pm 01:30 PM

In PHP development, the caching mechanism improves performance by temporarily storing frequently accessed data in memory or disk, thereby reducing the number of database accesses. Cache types mainly include memory, file and database cache. Caching can be implemented in PHP using built-in functions or third-party libraries, such as cache_get() and Memcache. Common practical applications include caching database query results to optimize query performance and caching page output to speed up rendering. The caching mechanism effectively improves website response speed, enhances user experience and reduces server load.

APCu Best Practices: Improving the Efficiency of Your Applications APCu Best Practices: Improving the Efficiency of Your Applications Mar 01, 2024 pm 10:58 PM

Optimizing Cache Size and Cleanup Strategies It is critical to allocate appropriate cache size to APCu. A cache that is too small cannot cache data effectively, while a cache that is too large wastes memory. Generally speaking, setting the cache size to 1/4 to 1/2 of the available memory is a reasonable range. Additionally, having an effective cleanup strategy ensures that stale or invalid data is not kept in the cache. You can use APCu's automatic cleaning feature or implement a custom cleaning mechanism. Sample code: //Set the cache size to 256MB apcu_add("cache_size",268435456); //Clear the cache every 60 minutes apcu_add("cache_ttl",60*60); Enable compression

The relationship between CPU, memory and cache is explained in detail! The relationship between CPU, memory and cache is explained in detail! Mar 07, 2024 am 08:30 AM

There is a close interaction between the CPU (central processing unit), memory (random access memory), and cache, which together form a critical component of a computer system. The coordination between them ensures the normal operation and efficient performance of the computer. As the brain of the computer, the CPU is responsible for executing various instructions and data processing; the memory is used to temporarily store data and programs, providing fast read and write access speeds; and the cache plays a buffering role, speeding up data access speed and improving The computer's CPU is the core component of the computer and is responsible for executing various instructions, arithmetic operations, and logical operations. It is called the "brain" of the computer and plays an important role in processing data and performing tasks. Memory is an important storage device in a computer.

See all articles