Hibernate cache and hibernate Cache Mechanism

Source: Internet
Author: User

Hibernate cache and hibernate Cache Mechanism
I. Hibernate cache Overview

Hibernate provides two levels of cache: first-level cache and second-level cache.

1. The first-level cache is a Session-level cache that belongs to the scope of transactions. The first-level cache is managed by hibernate.

2. the second-level cache is a sessionFactory-level cache that belongs to the process scope. The second-level cache can be divided into "built-in cache" and "external cache". The built-in cache: it is what hibernate will load when creating sessionFactory. hbn. xml files and some default SQL statements will be initialized in the memory. The built-in cache is read-only. external cache (second-level cache), sessionFactory will not start this cache plug-in by default, data in the external cache is the copy of data in the database, and the storage physical medium can be memory or hard disk.

Ii. Hibernate primary Cache

Session cache has two major functions:

1. reduce the frequency of accessing the database.

2. Ensure that the relevant records in the database are consistent with those in the cache.

The Session executes related SQL statements based on the latest properties of the dirty object to ensure synchronization between the relevant records in the database and the response objects in the cache. By default, the session clears the cache at the following time points:

1. When the application calls the commit () method of Transaction, commit () clears the cache and then submits transactions to the database.

2. The application performs some query operations. When the attributes of the cached Persistent Object change.

3. explicitly call the flush () method of the Session.

Session provides two methods to manage the cache:

1. evict (Object obj); clear a Specific Persistent Object from the cache.

2. clear (); clear all persistent objects in the cache.

Iii. Hibernate secondary Cache

1. Steps for using Hibernate second-level cache:

1) Add the jar package and configuration file of the second-level cache plug-in:

I. Copy \ hibernate-release-4.2.4.Final \ lib \ optional \ ehcache \ *. jar to the class path of the current Hibrenate application.
II. Copy hibernate-release-4.2.4.Final \ project \ etc \ ehcachexml to the class path of the current WEB Application

2) Configure hibernate. cfg. xml

I. Configure to enable the hibernate secondary Cache
<Property name = "cache. use_second_level_cache"> true </property>

II. products used to configure the hibernate second-level cache
<Property name = "hibernate. cache. region. factory_class"> org. hibernate. cache. ehcache. EhCacheRegionFactory </property>

III. Configure which classes use hibernate's secondary Cache
<Class-cache usage = "read-write" class = "com. atguigu. hibernate. entities. Employee"/>

In fact, you can also configure the second-level cache and second-level cache policies for which classes are used in the. hbm. xml file.

2). Set level-2 Cache Configuration

I. Configure second-level cache for the set

<Collection-cache usage = "read-write" collection = "com. atguigu. hibernate. entities. Department. emps"/>

You can also configure it in the. hbm. xml file.

<Set name = "emps" table = "GG_EMPLOYEE" inverse = "true" lazy = "true">
<Cache usage = "read-write"/>
<Key>
<Column name = "DEPT_ID"/>
</Key>
<One-to-learn class = "com. atguigu. hibernate. entities. Employee"/>
</Set>

II. Note: you also need to configure the persistence class corresponding to the elements in the set to use level 2 cache! Otherwise, n more SQL statements will be generated.

3). ehcache configuration file: ehcache. xml

4) query cache: by default, the configured cache is invalid for HQL and QBC queries, but it can be valid in the following ways:

I. Declare enable query cache in the hibernate configuration file

<Property name = "cache. use_query_cache"> true </property>

II. Call the setCacheable (true) method of Query or Criteria
@ Test
Public void testQueryCache (){
Query query = session. createQuery ("FROM Employee ");
Query. setCacheable (true );

List <Employee> emps = query. list ();
System. out. println (emps. size ());

Emps = query. list ();
System. out. println (emps. size ());

Criteria criteria = session. createCriteria (Employee. class );
Criteria. setCacheable (true );
}
III. the query cache depends on the second-level cache (the premise of using the query cache is to configure the hibernate second-level cache)

Example:

Department. java class:

package com.atguigu.hibernate.entities;import java.util.HashSet;import java.util.Set;public class Department {private Integer id;private String name;private Set<Employee> emps = new HashSet<>();public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Set<Employee> getEmps() {return emps;}public void setEmps(Set<Employee> emps) {this.emps = emps;}@Overridepublic String toString() {return "Department [id=" + id + "]";}}

Department. hbm. xml file Configuration:

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

Employee. java class:

package com.atguigu.hibernate.entities;public class Employee {private Integer id;private String name;private float salary;private String email;private Department dept;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public float getSalary() {return salary;}public void setSalary(float salary) {this.salary = salary;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public Department getDept() {return dept;}public void setDept(Department dept) {this.dept = dept;}@Overridepublic String toString() {return "Employee [id=" + id + "]";}public Employee(String email, float salary, Department dept) {super();this.salary = salary;this.email = email;this.dept = dept;}public Employee() {// TODO Auto-generated constructor stub}}

Configuration of the Employee. hbm. xml file:

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

Hibernate. cfg. xml file Configuration:

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE hibernate-configuration PUBLIC "-// Hibernate/Hibernate Configuration DTD 3.0 // EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 

Ecache. xml file configuration and method description:

<Ehcache> <! -- Sets the path to the directory where cache. data files are created. if the path is a Java System Property it is replaced by its value in the running VM. the following properties are translated: user. home-User's home directory user. dir-User's current working directory java. io. tmpdir-Default temp file path --> <! -- Specify a directory: When EHCache writes data to the hard disk, it writes the data to this directory. --> <diskStore path = "d :\\ tempDirectory"/> <! -- Default Cache configuration. these will applied to caches programmatically created through the CacheManager. the following attributes are required for defaultCache: maxInMemory-Sets the maximum number of objects that will be created in memory eternal-Sets whether elements are eternal. if eternal, timeouts are ignored and the element is never expired. timeToIdleSeconds-Sets the time to idle For an element before it expires. is only used if the element is not eternal. idle time is now-last accessed time timeToLiveSeconds-Sets the time to live for an element before it expires. is only used if the element is not eternal. TTL is now-creation time overflowToDisk-Sets whether elements can overflow to disk when the in-memory cache has reached the maxInMemory limit. --> <! -- Set the default cache data expiration Policy --> <defaultCache maxElementsInMemory = "10000" eternal = "false" timeToIdleSeconds = "120" timeToLiveSeconds = "120" overflowToDisk = "true"/> <! -- Set a data expiration Policy for the named cache. Each named cache represents a cache region (region): A cache block with a name. You can set different cache policies for each cache block. If no cache region is set, All cached objects use the default Cache Policy. That is: <defaultCache.../> Hibernate stores different classes/sets in different cache regions. For a class, the region name is the class name. For example: com. atguigu. domain. Customer for a set, the region name is the class name plus attribute name. For example, com. atguigu. domain. Customer. orders --> <! -- Name: Set the cache name. The value is the name of the fully qualified class name or set of classes. maxElementsInMemory: set the maximum number of objects that can be stored in the memory-based Cache. eternal: set whether the object is permanent. true indicates that the object will never expire. The timeToIdleSeconds and timeToLiveSeconds attributes are ignored. The default value is false timeToIdleSeconds: sets the maximum idle time of the object, in seconds, the object expires. When an object expires, EHCache clears it from the cache. If the value is 0, the object can be idle indefinitely. TimeToLiveSeconds: sets the maximum time for an object to survive. If the maximum time is exceeded, the object expires. If the value is 0, the object can be stored in the cache indefinitely. this attribute value must be greater than or equal to the value of timeToIdleSeconds overflowToDisk: After the number of objects in the memory-based Cache reaches the upper limit, whether to write the overflow object to the hard disk-based cache --> <cache name = "com. atguigu. hibernate. entities. employee "maxElementsInMemory =" 1 "eternal =" false "timeToIdleSeconds =" 300 "timeToLiveSeconds =" 600 "overflowToDisk =" true "/> <cache name =" com. atguigu. hibernate. entities. department. emps "maxElementsInMemory =" 1000 "eternal =" true "timeToIdleSeconds =" 0 "timeToLiveSeconds =" 0 "overflowToDisk =" false "/> </ehcache>

Usage of the second-level cache query cache:

@Testpublic void testQueryCache(){Query query = session.createQuery("FROM Employee");query.setCacheable(true);List<Employee> emps = query.list();System.out.println(emps.size());emps = query.list();System.out.println(emps.size());Criteria criteria = session.createCriteria(Employee.class);criteria.setCacheable(true);}

Optimization of the second-level query cache:

@ Testpublic void testQueryIterate () {Department dept = (Department) session. get (Department. class, 70); System. out. println (dept. getName (); System. out. println (dept. getEmps (). size (); Query query = session. createQuery ("FROM Employee e WHERE e. dept. id = 80 ");/*** use query. the list () method queries all the fields of the Employee, and uses the reflection mechanism to assemble them into a List <Employee> object * // List <Employee> emps = query. list (); // System. out. println (emps. size ();/*** query. iterator () queries only the id field and finds objects from the second-level cache based on the id. If there is a second-level cache, it is assembled, the second-level cache is no longer found from the database * It does not need to generate a batch of Employee object Assembly sets in the memory. * This method requires: * 1. the queried data table contains a large number of fields * 2. enable the second-level cache, and the second-level cache may contain the objects to be queried. Otherwise, it will be terrible, each object */Iterator <Employee> empIt = query is queried from the database by id. iterate (); while (empIt. hasNext () {System. out. println (empIt. next (). getName ());}}

Description of Timestamp cache regions:

Public void testUpdateTimeStampCache () {Query query = session. createQuery ("FROM Employee"); query. setCacheable (true); List <Employee> emps = query. list (); System. out. println (emps. size (); Employee employee = (Employee) session. get (Employee. class, 100); employee. setSalary (30000); // The select statement is executed before the update statement is executed, then execute the select statement/*** timestamp. The cache area stores the timestamp of the insert, update, or delete operations on the tables related to the query results. * Hibernate uses the timestamp cache area to determine whether the cached query results have expired. The running process is as follows: * perform the query operation at T1 and store the query results in the QueryCache area, record the timestamp of this region as T1 * T2 to update the table related to the query results. Hibernate stores the time of T2 in the UpdateTimestampCache region. * Before the query result is executed at the time T3, the timestamp in the QueryCache region and the timestamp in the UpdateTimestampCache region are compared. * If T2> T1, the query results originally stored in the QueryCache region are discarded, query data again in the database and store the results in the QueryCache area. * If T2 <T1, query results are obtained directly from QueryCache */emps = query. list (); System. out. println (emps. size ());}

  

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.