Hibernate level two cache and Ehcache configuration

Source: Internet
Author: User

Objective

This time the main review of Hibernate's level two cache of knowledge, configuration and use. The second level cache mainly uses the third party's Ehcache, will also introduce the Ehcache cache the related configuration attribute as well as in the project construction, the concrete project to view the next article maven constructs the Springmvc+hibernate project detailed solution article. (previously used hibernate two cache, but did not build and research, now spent half a day to build a bit, write down for your reference)

1. Hibernate level Two cache

Hibernate includes a cache of two levels:

1, first-level cache: The default is always enabled by the session level.

2, Level Two cache: optional sessionfactory level.

Session level and cache are always valid, when the application remains persistent entity, modify persisted entity, the session does not let this change flush to the database, but cached in the current session of the first level cache, unless the program displays the flush method to invoke the session, Or the query closes the session, it will change the one-time flush to the underlying database, which can reduce the interaction with the database, thereby improving the database access performance.

Sessionfactory level Two cache is global, all seeion of the application share this level two cache, when the session needs to crawl the data, the session will take precedence from the two-level cache crawl. (mainly including entity cache, query cache).

2. Scope of application

It is primarily suitable for the following data to be placed in level two cache:

1. Rarely modified, a large number of queries

2. Data that is not very important, allowing occasional concurrent access

3. Hibernate level Two cache configuration

Hibernate's level two caches primarily use third-party cache plug-ins, where Ehcache two caches are used primarily.

First, we need to map the Ehcache package and the Hibernate-ehcache package, MAVEN's pom.xml into the following:

               <!--hibernate--><dependency><groupid>org.hibernate</groupid><artifactid> Hibernate-core</artifactid><version>4.3.8.final</version></dependency><dependency ><groupId>org.hibernate</groupId><artifactId>hibernate-ehcache</artifactId>< version>4.3.8.final</version></dependency><!--Level Two cache Ehcache--><dependency><groupid >net.sf.ehcache</groupid><artifactid>ehcache</artifactid><version>2.9.0</version ></dependency>

Second, we need to set the information about level two cache in Hibernate's configuration file

<!--turn on level two cache Ehcache--><prop key= "Hibernate.cache.use_second_level_cache" >true</prop><!-- Turn on the level two cache of the query  if you do not need to set--><prop key= "Hibernate.cache.use_query_cache" >true</prop><!-- Hibernate4.0 above settings factory--><prop key= "Hibernate.cache.region.factory_class" > org.hibernate.cache.ehcache.ehcacheregionfactory</prop><!--The configuration file location for level two cache Ehcache--><prop key= " Hibernate.cache.provider_configuration_file_resource_path ">ehcache.xml</prop>

Cache mappings for two-level cache entities and attributes in general hibernate, and if the query data needs to be cached at level two, it needs to be opened using Hibernate.cache.use_query_cache.

4, the Ehcache configuration

The configuration file for Ehcache.xml is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><ehcache xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: Nonamespaceschemalocation= ". /config/ehcache.xsd "><diskstore path=" Java.io.tmpdir/ehcache "/><!--defaultcache setting. --     <defaultcache            maxelementsinmemory= "$"            eternal= "false"            timetoidleseconds= "300"            timetoliveseconds= "maxelementsondisk="            1000000 "            overflowtodisk=" true "             memorystoreevictionpolicy= "LRU" >                </defaultCache><!--Special objects setting.--><!--< Cache      name= "Org.andy.work.entity.AcctUser" maxelementsinmemory= "2" memorystoreevictionpolicy= "LRU"  Eternal= "true"  diskpersistent= "false" overflowtodisk= "false"  maxelementsondisk= "1000000"/> "-- </ehcache>

The first paragraph is to configure the default Ehcache level two cache information, and the second segment is a special configuration (when special configuration is required).

4.1. Detailed Configuration

    Name: the cache name.
    maxelementsinmemory: Maximum number of caches.
    Eternal: The object is permanently valid, but if set, timeout will not work.
    timetoidleseconds: Sets the allowable idle time (in seconds) for an object before it expires. An optional property is used only if the Eternal=false object is not permanently valid, and the default value is 0, which means that the idle time is infinite.
    timetoliveseconds: Sets the time (in seconds) that an object is allowed to survive before it expires. The maximum time is between the creation time and the expiration time. Used only when the Eternal=false object is not permanently valid, the default is 0, which means that the object survives indefinitely.
   Overflowtodisk: When the number of objects in memory reaches Maxelementsinmemory, Ehcache writes the object to disk.
   DISKSPOOLBUFFERSIZEMB: This parameter sets the buffer size of the Diskstore (disk cache). The default is 30MB. Each cache should have its own buffer.
   Maxelementsondisk: Maximum number of hard disk caches.
   Diskpersistent: Whether to cache VM Restart period data Whether The disk store persists between restarts of the virtual machine. The default value is False.
   diskexpirythreadintervalseconds: Disk failed thread run time interval, default is 120 seconds.
   Memorystoreevictionpolicy: When the maxelementsinmemory limit is reached, Ehcache will clean up the memory according to the specified policy. The default policy is LRU (least recently used). You can set it to FIFO (first in, out) or LFU (less used).
   Clearonflush: If the maximum amount of memory is cleared.

Note: Java.io.tmpdir Directory is : C:\Users\ login User \appdata\local\temp\ (window environment), so the above under My Computer directory below (already have cached content):

Of course the storage location we can be arbitrarily configured such as: <diskstore path= "D:/ehcache"/> is in the D disk under the Ehcache directory.

5. Configuration requires level two cache entities and attributes

This is only the form of annotations, in the form of XML is not said, most companies use annotations.

Enable level two cache usage on those collection properties for entity classes and entities

@Cache (usage = cacheconcurrencystrategy.read_write)

Note: If an entity requires a level two cache, the cache policy must also be specified if the entity contains attributes such as <set...>,<list...>.

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 = cacheconcurrency Strategy.read_write) public class Acctuser implements java.io.Serializable {/** * */private static final long Serialversio nuID = 6980093847795726310l;private string Id;private string nickname;private string telephone;private Date reGistertime;private set<acctrole> acctroles = new hashset<acctrole> (0);p ublic acctuser () {}public AcctUser ( String ID, string nickname) {this.id = Id;this.nickname = nickname;}  Public Acctuser (string ID, string nickname, String telephone,date registertime, set<acctrole> 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 = N) 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 = +) 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<acctrole> getacctroles () {return this.acctroles;} public void Setacctroles (set<acctrole> acctroles) {this.acctroles = Acctroles;}}

5.1. Cache usage Transaction Isolation mechanism

Usage provides the following types of transaction isolation mechanisms for cache objects:

(NONE, Read_Only, Nonstrict_read_write, Read_write, transactional)

The Ehcache does not support the transaction transaction mechanism, but the other three types can be used:

read-only::

Without modification, it can be read-only cache, note that under this policy, if you modify the database directly, even if you can see the foreground display effect,

However, modifying the object to the cache will report that Error,cache does not work. Another: Deleting a record will cause an error because the object in read-only mode cannot be deleted from the cache.

Read-write:

Need to update the data, it is appropriate to use a read/write cache, the premise: the database is not serializable transaction isolation level (serialization of transaction isolation levels)

Nonstrice-read-write:

It is more appropriate to use a non-strict read/write cache policy if you only occasionally need to update the data (that is, two transactions are not very common when updating the same record at the same time) and do not require very strict transaction isolation.

6. Using Query Caching

The key value cached by the query cache is the HQL or SQL statement used by the query, and it is important to note that the query cache requires not only the same HQL statement, the SQL statement, or even the same parameters that are passed in, so hibernate can check the data from the cache.

The query cache is like the next two steps:

1. Query cache does not only open Hibernate.cache.use_query_cache

2. You also need to use setcacheable at query time (true)

Public list<acctuser> findAll () {list<acctuser> acctusers = This.getcurrentsession (). CreateQuery ("from Acctuser "). Setcacheable (True). List (); return acctusers;}



Hibernate level two cache and Ehcache configuration

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.