Detailed Explanation of Hibernate Level 1 Cache and Level 2 Cache

  • 2021-07-10 19:50:17
  • OfStack

1. Level 1 cache-level 2 cache concept explanation

(1) Level 1 cache is Session level cache. An Session has done a query operation, and it will put the result of this operation in Level 1 cache. If this session (1 must be the same as an session) has done the same operation again in a short time, then hibernate will be directly taken from Level 1 cache, instead of connecting to the database and taking data;

(2) Level 2 cache is the SessionFactory level cache. As the name implies, the query results will be cached in the Level 2 cache when querying. If the same operation is performed with an session created by an sessionFactory, hibernate will take the results from the Level 2 cache instead of connecting to the database;

(3) Two levels of Cache are provided in Hibernate, and the first level cache is the Session level cache, which belongs to the transaction scope cache. This level 1 cache is managed by hibernate, and there is no intervention in 1 cases; Level 2 caches are SessionFactory level caches, which are process-scoped or cluster-scoped caches. This level 1 cache can be configured and changed, and can be dynamically loaded and unloaded. Hibernate also provides a query cache for query results, which relies on Level 2 cache;

2. Comparison of Level 1 and Level 2 caches

(1) Level 1 cache Level 2 cache stores data in the form of interrelated persistent objects, the scope of bulk data cache of objects, the scope of transaction, Each transaction has a separate Tier 1 cache process scope or cluster scope, The cache is shared by all transactions within the same process or cluster. Because each transaction has a separate level 1 cache, There is no concurrency problem and no need to provide a concurrency access policy. Since multiple transactions access the same data in the Level 2 cache at the same time, an appropriate concurrency access policy must be provided to ensure that a specific transaction isolation level data expiration policy does not provide a data expiration policy.

(2) Objects in Level 1 cache never expire, Unless the application explicitly empties the cache or purges specific objects, data expiration policies must be provided, such as the maximum number of objects in the memory-based cache, the maximum amount of time allowed for objects to remain in the cache, and the maximum amount of free time allowed for objects to remain in the cache physical storage media memory memory and hard disk.

(3) Bulk data of objects are first stored in the memory-based cache. When the number of objects in memory reaches the upper limit specified in the data expiration policy, the rest of the objects will be written into the hard disk-based cache.

(4) Software implementation of cache in the implementation of Session of Hibernate, the implementation of cache is provided by the third party, and Hibernate only provides cache adapter (CacheProvider). Used to integrate specific cache plug-ins into Hibernate.

(5) Enable caching as long as the application program performs the operations of saving, updating, deleting, loading and querying database data through Session interface, Hibernate will enable level 1 cache and copy the data in the database into the cache in the form of objects. For batch update and batch delete operations, if you don't want to enable level 1 cache, you can bypass Hibernate API and directly perform finger operations through JDBC API.

(6) Users can configure Level 2 caching at the granularity of a single class or a single collection of classes. If instances of a class are frequently read but rarely modified, you can consider using level 2 caching.

(7) Hibernate adds instances of a class or collection to the Level 2 cache at run time only if it is configured for the Class or Collection Level 2 cache. The physical medium of Level 1 cache is memory. Due to the limited memory capacity, the number of loaded objects must be limited by appropriate retrieval strategies and retrieval methods. The evit () method of Session explicitly empties specific objects in the cache, but it is not recommended. The physical media of Tier 2 cache can be memory and hard disk, so Tier 2 cache can store a large amount of data, and the maxElementsInMemory attribute value of data expiration policy can control the number of objects in memory.

(8) Managing Level 2 cache mainly includes two aspects: selecting persistent classes that need to use Level 2 cache and setting appropriate concurrent access policies; Choosing cache adapters and setting appropriate data expiration policies.

Management of Level 3.1 Cache

(1) When an application calls save (), update (), savaeOrUpdate (), get (), or load () of Session, and calls the list (), iterate (), or filter () methods of the query interface, Hibernate adds the corresponding object to the Level 1 cache if it does not already exist in the Session cache. When cleaning the cache, Hibernate synchronously updates the database according to the state changes of the objects in the cache. Session provides applications with two ways to manage the cache: evict (Object obj): Clear the persistent object specified by the parameter from the cache. clear (): Empty all persistent objects in the cache.

(2) save, update, saveOrupdate, load, list, iterate and lock will store data in level 1 cache;

save case:


 // Add 1 Students 
  Student student=new Student();
  student.setName(" Xiaodong ");
  s.save(student);// Put in 1 Level cache 
  // I'll check right away 
  Student stu2=(Student) s.get(Student.class, student.getId()); //select
  System.out.println(" The name of the student you just joined is "+stu2.getName());

(3) What operations fetch data from level 1 cache: get, load, list

get/load will be fetched from the level 1 cache first, if not. There are different operations [get will immediately send a request to the database, while load will return a proxy object, until the user really uses the data, will not send a request to the database;


// Query 45 Student No. 
  Student stu=(Student) s.get(Student.class, 45);
  System.out.println("|||||||||||||||||||");
  String hql="from Student where id=45";
  Student stu2=(Student) s.createQuery(hql).uniqueResult();
  System.out.println(stu2.getName());

From the above case, we can see that query. list () query. uniueResut () does not retard data from level 1! But query. list or query. uniqueRestu () will slow down the data to level 1.

Note:

Level 1 cache can be used without configuration, and it has no protection mechanism, so we programmers should consider this problem. We can clear the objects in session cache with evict or clear. evict is to clear one object, clear is to clear all sesion cache objects

② The life cycle of objects in session cache is automatically destroyed when session is closed.

③ We use HashMap to simulate an Session cache, so as to deepen the cache.

4. Hibernate Level 2 Cache Management

1. The general process of the Hibernate Level 2 cache policy is as follows:

1) When querying conditionally, always issue an select * from table_name where... (select all fields) to query the database and get all the data objects at one time.

2) Put all obtained data objects into level 2 cache according to ID.

3) When the Hibernate accesses the data object according to the ID, firstly, it is checked from the Session1 level cache; No, if level 2 cache is configured, look it up from level 2 cache; If you can't find it, query the database and put the results into the cache according to ID.

4) When deleting, updating and adding data, update the cache at the same time. Hibernate Level 2 caching policy is a caching policy for ID queries, but has no effect on conditional queries. To do this, Hibernate provides Query Cache for conditional queries.

5) Level 2 cached objects may be placed in memory or on disk.

2. What kind of data is suitable for storage in Level 2 cache?

1) Data that is rarely modified

2) Not very important data, allowing occasional concurrent data

3) Data that will not be accessed concurrently

4) Reference data refers to constant data for reference, which has a limited number of instances, whose instances are referenced by instances of many other classes, and whose instances are rarely or never modified.

3. Data that is not suitable for storage in Level 2 cache?

1) Frequently modified data

2) Concurrent financial data is absolutely not allowed

3) Data shared with other applications.

4. Common cache plug-ins Hibernater2 level cache is a plug-in. Here are several common cache plug-ins:

EhCache: It can be used as a process-wide cache, and the physical medium for storing data can be memory or hard disk, which supports the query cache of Hibernate.

OSCache: It can be used as a process-wide cache, and the physical medium for storing data can be memory or hard disk. It provides a rich cache data expiration policy and supports the query cache of Hibernate.

SwarmCache: Can be used as a cluster-wide cache, but does not support query caching for Hibernate.

JBossCache: Can be used as a cluster-wide cache, supports transactional concurrent access policies, and provides support for query caching in Hibernate.

5. Main steps to configure Hibernate Level 2 cache:

1) Select the persistence class that requires a Level 2 cache and set the concurrent access policy for its named cache. This is the most serious step to consider.

2) Select the appropriate caching plug-in and edit the plug-in's configuration file.


<property name="hbm2ddl.auto">update</property>
 <!--  Start 2 Level cache  -->
 <property name="cache.use_second_level_cache">true</property>
 <!--  Specify which type to use 2 Level cache  -->
 <property name="cache.provider_class">org.hibernate.cache.OSCacheProvider</property>
 <mapping resource="com/hsp/domain/Department.hbm.xml" />
 <mapping resource="com/hsp/domain/Student.hbm.xml" />
 <!--  Specify which domain Enable 2 Level cache  
  Special note 2 Level cache strategy :
 1. read-only
 2. read-write
 3. nonstrict-read-write
 4. transcational
 -->
 <class-cache class="com.hsp.domain.Student" usage="read-write"/>

3) You can place the oscache. properties file in the src directory, so you can specify the size of the object capacity to be placed in the Level 2 cache. The default is 1000

6. Use Level 2 cache:


// TODO Auto-generated method stub
 // By obtaining 1 A sesion, Jean hibernate Framework operation (config-> Loading hibernate.cfg.xml)
 Session s=null;
 Transaction tx=null;
 try {
  // We use the basic template to explain .
  s=HibernateUtil.openSession();
  tx=s.beginTransaction();
  // Query 45 Student No. 
  Student stu1=(Student) s.get(Student.class, 45);//45->1 Level cache  
  System.out.println(stu1.getName());
  tx.commit();
 } catch (Exception e) {
  e.printStackTrace();
  if(tx!=null){
  tx.rollback();
  }
 }finally{
  if(s!=null && s.isOpen()){
  s.close();
  }
 }
 System.out.println("*********************************");
 try {
  // We use the basic template to explain .
  s=HibernateUtil.openSession();
  tx=s.beginTransaction();
  // Query 45 Student No. 
  Student stu1=(Student) s.get(Student.class, 45); 
  System.out.println(stu1.getName());
  
  Student stu3=(Student) s.get(Student.class, 46); 
  System.out.println(stu3.getName());
  tx.commit();
 } catch (Exception e) {
  e.printStackTrace();
  if(tx!=null){
  tx.rollback();
  }
 }finally{
  if(s!=null && s.isOpen()){
  s.close();
  }
 }
 // Finish 1 Statistics, statistical information in Sessfactory
 //SessionFactory Object .
 Statistics statistics= HibernateUtil.getSessionFactory().getStatistics();
 System.out.println(statistics);
 System.out.println(" Put in "+statistics.getSecondLevelCachePutCount());
 System.out.println(" Hit "+statistics.getSecondLevelCacheHitCount());
 System.out.println(" Miss "+statistics.getSecondLevelCacheMissCount());

After configuring level 2 cache, please note that you can check your configuration hit rate through Statistics

Summarize


Related articles: