Hibernate review cache mechanism-first level cache, level two cache, query cache

Source: Internet
Author: User

before we introduce the caching mechanism of hibernate, let's look at what the cache is:
Cache: A very general concept in the computer domain. Put something in it. The cache is a collection. It is between an application and a persistent data storage source, such as a file on a hard disk or a database, to reduce the frequency with which the application directly reads and writes to the persistent data storage source, thereby improving the performance of the application. The data in the cache is a copy of the data in the data storage source and the cached physical media is usually memory.
Everyone who understands JDBC knows that when it comes to connecting to a database, it usually makes a connection pool, so what's the difference between a connection pool and a cache?
The same point: both can be in memory, implementation is the same, is to improve performance.
The difference: The connection pool is a heavy-weight pool, which means that the resources inside the pool are very valuable things.

Let's look at the caching mechanism in Hibernate: First level cache, level two cache, query cache.

First- level cache:
1, in Hibernate, a thread corresponds to a session, a thread can be regarded as a session, that is, the session is bound together with the thread.
2, understand the first level cache:
A series of Java interfaces are included in the session interface, which forms a level one cache at session level, so long as the lifetime of the session instance is not over, the cached objects stored therein will not die. Iterate, load, get, save, and so on use a first-level cache.
3, first-level cache cleanup
Session has a cache, the object in the cache is called a persistent object, he and the database related records, the session at some point in time, according to the changes in the cache objects to execute the relevant SQL statements, to synchronize the update database, this process is called clean cache, By default, the session cleans up the cache at the following point in time:
(1) When committing a transaction, the cache Session.flush () is cleared first;
(2) When a persisted object in the cache changes, the cache is cleaned up to ensure the latest state of the persisted object.
(3) Display call Session.flush ();
Clean up the relevant knowledge points:
Session.flush (); the cache will be cleaned, the cache will not be lost, and the INSERT statement will be generated.
Session.clear () empties the cache, and the persisted object in the cache is lost.
Session.reflush () lets the session and the database synchronize, executes the query, displays the latest information of the database, and updates the state of the locally cached object.
When the session loads an object, the properties of the value type of the object are copied a snapshot, and when the cache is cleaned, the object's properties are determined by comparing the object's current properties and snapshots.
The executing SQL statement changes, without changing the SQL statement:
When you clean up the cache without using refresh, the objects in the first-level cache are compared to the objects in the snapshot, and the Updata statements are generated when the message is submitted.
4. Other points of knowledge
iter = Session.createquery ("From Student s where s.id<5"). Iterate ();
while (Iter.hasnext ()) {
Student Student = (Student) iter.next ();
System.out.println (Student.getname ());
Iterate there is a n+1 problem if the cache is not used.
The first time the iterate query emits a N+1 SQL statement, the first SQL statement queries all IDs, and then queries the entity object based on the ID, with n IDs issuing n statements to query the entity.
Iterate queries for different properties, one-tier caches are not cached because the first-level cache is used to cache entity objects.

There is no one-level cache between sessions, and a first-level cache is invalidated by the demise of the session.


Second-level cache:

1, level Two cache needs sessionfactory to manage, is the process level of the cache, everyone can use, is shared.
2, two level cache is more complex, generally with third-party products, hibernate only provides a simple implementation, with Hashtable implementation.
3, the use of the occasion: long time unchanged data.
4. Configuration steps:
(1) Ehcache.xml can be set by default, all classes follow this configuration, or they can be configured separately for an object.
(2) in the Hibernate.cfg.xml configuration file configuration cache, let hibernate know that we are using that level two cache. Includes configuration properties: whether to enable two-level cache, level two cache providers.
(3) manually specify which entity class objects are put into the cache, in the Hibernate.cfg.xml configuration
<class-cache class= "com.bjpowernode.hibernate.Student" usage= "Read-only"/>
Or
<cache usage= "Read-only" in front of the ID label in the mapping file/>
The Usage property represents a policy that uses caching, and generally takes precedence over the use of read-only, which means that if the data is put into the cache, it cannot be modified because the data that is often modified does not need to be placed in the cache.
The read-only strategy is efficient because the cache cannot be changed, but the problem of dirty data can occur, and the solution to this problem can only depend on the cache timeout, because the data of the possible objects is modified, but
The cache does not change, causing the data to be out of sync, which is the problem of dirty data.
Read-write when the persistence object changes, the cache will change, and the database changes, this way need to add locks, efficiency than read-only slow.
5, Knowledge points:
The secondary cache must be sessionfactory managed, let the sessionfactory be cleared, and the evict method can be called.
After querying the data will be placed by default in level two and first level cache, we can also control the query out of the data is not put into the cache, that is, we can control the first-level cache and two-level cache exchange.
Session.setcachemode (cachemode.ignore); Prevents data in the first-level cache from being placed in the level two cache.
As with the first-level cache, the level two cache does not store query data for normal properties, which is the same as the first-level cache, which only holds entity objects.
Session-level caching does not make much sense to improve performance because the life cycle is too short.

Query cache:
1, first-level cache and level two cache are only the entity object, if the query entity object of the normal properties of data, can only be placed in the query cache, the query cache also holds the ID of the query entity object.
2. The life cycle of the query cache is indeterminate, and the lifecycle of the query cache ends when the associated table changes (through Hibernate).
3, the query cache is closed by default, you can configure <property name= "Hibernate.cache.use_query_cache" >true</property> in Hibernate.cfg.xml. And the query cache must be started manually in the program, and the Setcacheable (True) method in the query interface is enabled.
4, query cache meaning is not very large, the query cache said that is stored by the list method or iterate method query data, we rarely appear in the query the exact same condition query, that is, the low hit rate,
The data in this cache is always changing. This caching configuration makes sense unless multiple queries are queries that query the same criteria, which means that the returned results are always the same.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.