Hibernate second-level cache and ehcache Configuration
Preface
This time, I will mainly review the knowledge, configuration, and usage of Hibernate's second-level cache. The second-level cache mainly uses third-party ehcache. It also introduces the configuration attributes of the ehcache cache and the construction in the project. For details about the project, refer to the nextMaven build SpringMVC + Hibernate project details. (I used Hibernate's second-level cache before, but I didn't build and study it myself. Now I spent half a day building it and writing it down for your reference)
1. Hibernate second-level cache
Hibernate includes two levels of cache:
1. Level 1 cache: The session level is always enabled by default.
2. Level-2 Cache: Optional SessionFactory level.
Session-level and cache are always valid. When an application maintains a Persistent Object and modifies a persistent object, the Session does not flush the object to the database, but is cached in the current Session level cache, only when the program shows that the flush method of the session is called, or when the session is closed is queried, the flush method will be changed once to the underlying database, which can reduce interaction with the database, this improves the database access performance.
The SessionFactory level second-level cache is global, and all Seeion of the application shares this second-level cache. When the Session needs to capture data, the Session will first capture data from the second-level cache. (Mainly including object cache and query cache ).
2. Applicability
It is mainly applicable to the following data into the second-level cache:
1. Rarely modified, a large number of queries
2. Not very important data, allowing occasional concurrent access
3. Hibernate second-level cache Configuration
The second-level cache of Hibernate mainly uses third-party cache plug-ins. Here, the second-level cache of Ehcache is used.
First, we need to map the ehcache package and the hibernate-ehcache package. The maven pom. xml is reflected as follows:
Org. hibernate
Hibernate-core
4.3.8.Final
Org. hibernate
Hibernate-ehcache
4.3.8.Final
Net. sf. ehcache
Ehcache
2.9.0
Second, we need to set level-2 Cache Information in the Hibernate configuration file.
True
True
Org. hibernate. cache. ehcache. EhCacheRegionFactory
Ehcache. xml
Generally, the cache ing between the second-level cache entities and attributes of Hibernate needs to be enabled using hibernate. cache. use_query_cache if you need to cache the query data.
4. Ehcache Configuration
The configuration file of ehcache. xml is as follows:
The first section is to configure the default ehcache level-2 Cache Information, and the second section is a special configuration (when special configuration is required ).
4.1 configuration details
Name: cache name.
MaxElementsInMemory: Maximum number of caches.
Eternal: whether the object is permanently valid. Once set, timeout does not work.
TimeToIdleSeconds: sets the allowable idle time before the object expires (unit: seconds ). This attribute is optional only when the eternal = false object is not permanently valid. The default value is 0, indicating that the idle time is infinite.
TimeToLiveSeconds: sets the allowed lifetime of an object before it expires (unit: seconds ). The maximum time is between the creation time and the expiration time. It is used only when the eternal = false object is not permanently valid. The default value is 0. That is, the object survival time is infinite.
OverflowToDisk: when the number of objects in the memory reaches maxElementsInMemory, Ehcache writes the objects to the disk.
DiskSpoolBufferSizeMB: this parameter sets the cache size of DiskStore (disk cache. The default value is 30 MB. Each Cache should have its own buffer.
MaxElementsOnDisk: Maximum number of Hard Disk caches.
DiskPersistent: Indicates Whether to cache data during VM restart. Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
DiskExpiryThreadIntervalSeconds: Specifies the interval for running a disk failure thread. The default value is 120 seconds.
MemoryStoreEvictionPolicy: When the maxElementsInMemory limit is reached, Ehcache clears the memory according to the specified policy. The default policy is LRU (least recently used ). You can set it to FIFO (first-in-first-out) or LFU (rarely used ).
ClearOnFlush: whether to clear when the maximum number of memory is exceeded.
Note:Java. io. the tmpdir directory is C: \ Users \ Login User \ AppData \ Local \ Temp \ (in the window environment). Therefore, the directory on my computer is as follows (cache content already exists):
Of course, we can configure the storage location at will, for example: The ehcache directory under drive D.
5. Configure level-2 Cache entities and attributes
Here we will only introduce the annotation form. xml is not mentioned, and most companies use annotations.
Enable second-level cache on the collection attributes of object classes and objects
@ Cache (usage = CacheConcurrencyStrategy. READ_WRITE)
Note: if an object requires second-level caching, if the object contains , You must specify the cache policy.
As follows:
package org.andy.work.entity;// Generated 2015-2-3 10:43:00 by Hibernate Tools 4.0.0import java.util.Date;import java.util.HashSet;import java.util.Set;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.FetchType;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.JoinTable;import javax.persistence.ManyToMany;import javax.persistence.Table;import javax.persistence.Temporal;import javax.persistence.TemporalType;import org.hibernate.annotations.Cache;import org.hibernate.annotations.CacheConcurrencyStrategy;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;/** * AcctUser generated by hbm2java */@Entity@Table(name = "acct_user", catalog = "work")@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)public class AcctUser implements java.io.Serializable {/** * */private static final long serialVersionUID = 6980093847795726310L;private String id;private String nickName;private String telephone;private Date registerTime;private Set acctRoles = new HashSet(0);public AcctUser() {}public AcctUser(String id, String nickName) {this.id = id;this.nickName = nickName;}public AcctUser(String id, String nickName, String telephone,Date registerTime, Set acctRoles) {this.id = id;this.nickName = nickName;this.telephone = telephone;this.registerTime = registerTime;this.acctRoles = acctRoles;}@Id@Column(name = "id", unique = true, nullable = false, length = 36)public String getId() {return this.id;}public void setId(String id) {this.id = id;}@Column(name = "nick_name", nullable = false)public String getNickName() {return this.nickName;}public void setNickName(String nickName) {this.nickName = nickName;}@Column(name = "telephone")public String getTelephone() {return this.telephone;}public void setTelephone(String telephone) {this.telephone = telephone;}@Temporal(TemporalType.TIMESTAMP)@Column(name = "register_time", length = 19)public Date getRegisterTime() {return this.registerTime;}public void setRegisterTime(Date registerTime) {this.registerTime = registerTime;}@JsonIgnoreProperties(value={"acctUsers", "acctAuthorities"})@ManyToMany(fetch = FetchType.LAZY)@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)@JoinTable(name = "acct_user_role", catalog = "work", joinColumns = { @JoinColumn(name = "user_id", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "role_id", nullable = false, updatable = false) })public Set getAcctRoles() {return this.acctRoles;}public void setAcctRoles(Set acctRoles) {this.acctRoles = acctRoles;}}
5.1 Cache usage transaction isolation mechanism
Usage provides the following transaction isolation mechanisms for cached objects:
(NONE, READ_ONLY, NONSTRICT_READ_WRITE, READ_WRITE, TRANSACTIONAL)
Ehcache does not support the transaction mechanism, but the other three can be used:
Read-only ::
You do not need to modify it, so you can perform read-only caching on it. Note that in this policy, if you directly modify the database, even if you can see the front-end display effect,
However, when an object is modified to the cache, an error is reported, and the cache does not work. In addition, an error is returned when you delete a record because the read-only mode object cannot be deleted from the cache.
Read-write:
To update data, it is more appropriate to use the read/write cache. premise: the database cannot think of serializable transaction isolation level (serialization transaction isolation level)
Nonstrice-read-write:
Only data needs to be updated occasionally (that is, it is uncommon for two transactions to update the same record at the same time), and strict transaction isolation is not required, therefore, it is more suitable to use non-strict read/write cache policies.
6. Use query Cache
The key value cached in the query cache is the HQL or SQL statement used for the query,Note that:The query cache requires that not only the HQL statements and SQL statements used are the same, but even the input parameters are the same, so that Hibernate can retrieve data from the cache.
The following two steps are taken to query the cache:
1. Not only hibernate. cache. use_query_cache is enabled for query cache
2. You also need to use setCacheable (true) during query)
public List findAll() {List acctUsers = this.getCurrentSession().createQuery("from AcctUser").setCacheable(true).list();return acctUsers;}