Hibernate level cache and level two cache depth comparison

Source: Internet
Author: User
Tags set set hazelcast

1. What is a cache

Caching is between an application and a physical data source , and it is designed to reduce the frequency of application access to physical data sources, thereby improving the performance of the application. The data in the cache is a copy of the data in the physical data source, the application reads and writes data from the cache at run time, and at a particular moment or event synchronizes the cache and the data from the physical data source.

The cached media is generally memory, so the read and write speed is very fast. However, if the amount of data stored in the cache is very large, the hard disk is also used as the cache medium. The implementation of the cache not only takes into account the stored media , but also considers the concurrent access to manage the cache and the life cycle of the cached data .

Hibernate's first-level cache is built-in and cannot be uninstalled.

Hibernate's Level Two cache is a cache of sessionfactory, which can be divided into built-in caches and external caches , and the built-in cache is hibernate-only and cannot be uninstalled. Normally during hibernate initialization, hibernate places the mapping metadata and the predefined SQL statements into the sessionfactory cache, where the mapping metadata is the copy of the data in the mapping file, and the predefined SQL statements are Hibernate based on the number of mapped elements It was pulled out. The built-in cache is read-only. An external cache is a configurable cache plug-in that, by default, Sessionfactory does not start a level two cache, requires the user to import a third-party plug-in, and two-level cache is configured in the Hibernate.cfg.xml file. The data in the external cache is a copy of the database data, and the external cached physical media can be either memory or hard disk.

2.Hibernate Cache Configuration

Hibernate's first level cache and level two built-in cache are self-bringing, non-unmounted, and no configuration required.

Below we mainly introduce the configuration of level two external cache plug-in, here are several common cache plug-ins:

    • EhCache: As a process-wide cache, the physical media that holds the data can be either memory or hard disk, which provides support for Hibernate's query caching.
    • Oscache: As a process-wide cache, the physical media that holds the data can be either memory or hard disk, providing a rich cache data expiration policy that supports Hibernate's query caching.
    • Swarmcache: Can be used as a cluster-wide cache but does not support Hibernate's query cache.
    • JBossCache: Can be used as a cluster-wide cache, supports transactional concurrency access policies, and provides support for hibernate query caching.
    • Memcached: Can be used as a cluster-wide cache, supports transactional concurrency access policies, does not support region
    • Redis
    • GemFire
    • hazelcast: Under cluster, can support read and write

Hazelcast Configuration Reference: https://github.com/hazelcast/hazelcast-code-samples/tree/master/hazelcast-integration/ Hibernate-2ndlevel-cache

Redis: Configuration Reference Https://github.com/debop/hibernate-redis

EhCache:

Sessionfactory Configuration injection:

<propKey= "Hibernate.cache.use_query_cache">True</prop><propKey= "Hibernate.cache.use_second_level_cache">True</prop><propKey= "Hibernate.cache.provider_class">Org.hibernate.cache.EhCacheProvider</prop>

*.hbm.xml Configuration changes (note:Ehcache does not support transactional, the other three kinds can be supported.) )

<name= "Com.hoo.hibernate.entity.User"  table= "User"  lazy  = "false"><usage= "transactional|read-write| Nonstrict-read-write|read-only "/>

Hibernatetemplate Injection Modification

<BeanID= "Hibernatetemplate"class= "Org.springframework.orm.hibernate3.HibernateTemplate">    < Propertyname= "Sessionfactory">       <refBean= "Sessionfactory" />    </ Property>    < Propertyname= "Cachequeries">       <value>True</value>    </ Property></Bean>

Session call directly, modify

Session s =hibernatesessionfactory.getsession (); Criteria C= S.createcriteria (User.class); C.setcacheable (true);//This sentence must haveSYSTEM.OUT.PRINTLN ("first read"); List<User> users =c.list (); System.out.println (Users.size ()); Hibernatesessionfactory.closesession (); S=hibernatesessionfactory.getsession (); C= S.createcriteria (User.class); C.setcacheable (true);//This sentence must haveSystem.out.println ("second read"); Users=c.list (); System.out.println (Users.size ()); Hibernatesessionfactory.closesession ();

Ehcache.xml Configuration

<Cachename= "Com.hoo.hibernate.entity.User"maxelementsinmemory= "10000"Eternal= "false"Timetoidleseconds= "+"Timetoliveseconds= "All"Overflowtodisk= "true" /><!--hbm Files Find the policy for the cache method name: If you do not specify a property value for name in the region= "Ehcache.xml" in the hbm file, Use the cache with the name Com.hoo.hibernate.entity.User, or Defaultcache if there is no cache name that matches the class name. If user contains a set set, you need to specify its cache for example user contains Cityset collection, you need to add the following configuration to Ehcache.xml -<Cachename= "Com.hoo.hibernate.entity.citySet"maxelementsinmemory= "10000"Eternal= "false"Timetoidleseconds= "+"Timetoliveseconds= "All"Overflowtodisk= "true" /><Cachename= "Org.hibernate.cache.UpdateTimestampsCache"maxelementsinmemory= "the"Eternal= "true"Overflowtodisk= "true" /><Cachename= "Org.hibernate.cache.StandardQueryCache"maxelementsinmemory= "10000"Eternal= "false"Timetoliveseconds= "+"Overflowtodisk= "true" />

Debugging time Use log4j log4j.logger.org.hibernate.cache=debug, more convenient to see Ehcache operation process, mainly for debugging process, the actual application release, please comment out, so as not to affect performance.

3. The difference between a first-level cache and a two-level cache

The form of storing data; the former is an interrelated persistence object, which is the object's bulk data

The scope of the cache, the former is the transaction scope, each transaction has a separate first-level cache, which is a process-wide or cluster-wide, and the cache is shared across all transactions within the same process or cluster

Concurrent access policies, which do not have concurrency problems and do not provide concurrent access policies, which must provide appropriate concurrent access policies to guarantee specific transaction isolation levels

Data expiration policies that have no data expiration policy, such as the number of cached objects, the maximum amount of time an object is in the cache, and the maximum idle time the object is in the cache

Physical media, the former is memory, the latter is memory and hard disk

Cached software implementation, the former only because the implementation of Hibernate session contains the implementation of the cache, the latter is provided by a third-party cache adapter (Cacheprovider) for the specific cache plug-in integration into the

The way the cache is enabled, the former performs operations through the session interface, enabling caching, which requires the user to configure a second-level cache on the granularity of a single class or a single collection.

The way the cache is managed, the former can limit the number of loaded objects by retrieving policies and retrieval methods, the latter has two main aspects of managing the cache: A: Select the persistence class that needs to use the second level cache, set the appropriate concurrency access policy; B: Select the cache adapter and set the appropriate data expiration policy;

Hibernate level cache and level two cache depth comparison

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.