Hibernate cache and level two cache

Source: Internet
Author: User
Tags sesion

一、一级 caching Two-level cache concept Interpretation

(1) A cache is the session level cache, a session to do a query operation, it will put the results of this operation in a first-level cache, if a short period of time this

Session (must be the same session) and do the same operation, then hibernate directly from the first cache to take, and will not go to the database, fetch data;

(2) Level two cache is the sessionfactory level of cache, as the name implies, query results will be cached to the level two cache, if the same sessionfactory

When a session is created that performs the same action, Hibernate takes the result from the level two cache and no longer connects to the database;

(3) Hibernate provides a level two cache, and the first level of cache is session-level caching, which is a transaction-scoped cache. This level of caching is managed by hibernate

, generally without intervention; the second level of caching is the sessionfactory level of caching, which is a process-wide or cluster-wide cache. This level of other slow

Storage can be configured and changed, and can be dynamically loaded and unloaded. Hibernate also provides a query cache for query results, which relies on the second level cache;


Comparison of 二、一级 cache and level two cache

(1) First-level cache second-level cache holds data in the form of a wide range of data caches that are associated with persisted object objects in the bulk of a transaction scope, each transaction has a separate first level

Cache process scope or cluster scope, cache is shared by all transactions within the same process or cluster for concurrent access policies because each transaction has a separate first-level cache, no

concurrency issues occur without the need to provide concurrent access policies because multiple transactions access the same data in the second-level cache at the same time, an appropriate concurrency access policy must be provided to protect

Data expiration policy for a specific transaction isolation level does not provide a data expiration policy.

(2) objects in the first-level cache never expire unless the application explicitly empties the cache or

clearing a specific object must provide a data expiration policy, such as the maximum number of objects in the memory-based cache, allowing the object to be in the cache for the longest time, and allowing the object to

The maximum idle time in the cache physical storage media memory and hard disk.

(3) The bulk data of the object is first stored in the memory-based cache, when the number of objects in memory reaches the number

When the upper limit is specified in the expiration policy, the remaining objects are written to the hard disk-based cache.

(4) The cached software implementation includes the cache in the implementation of the hibernate session.

The implementation is provided by a third party, and hibernate only provides a cache adapter (Cacheprovider). Used to integrate specific cache plugins into hibernate.

(5) How to enable caching

Hibernate enables first-level caching as long as the application performs the operations of saving, updating, deleting, loading, and querying database data through the session interface, and the database

data is copied to the cache in the form of objects, for bulk updates and bulk Delete operations, if you do not want to enable first level caching, you can bypass the hibernate API and directly

Use the JDBC API to perform a finger operation.

(6) A user can configure a second-level cache on the granularity of a single collection of classes or classes. If an instance of a class is read frequently but is seldom modified, it

You might consider using a second-level cache.

(7) Only a second level cache is configured for a class or collection, and Hibernate adds its instance to the second level cache at run time.

User How to manage caching the first-level cache of physical media is memory, and due to limited memory capacity, the number of loaded objects must be limited by appropriate retrieval policies and retrieval methods.

The Evit () method of the session can explicitly empty the cache for specific objects, but this method is not recommended. The second-level cache of physical media can be memory and hard disk, so the second

Level caches can hold large amounts of data, and the Maxelementsinmemory property value of the data expiration policy can control the number of objects in memory.

(8) The management of the second level cache mainly includes two aspect: Select the persistence class that needs to use the second level cache, set the appropriate concurrency access policy: Select the cache adapter, and set the appropriate data expiration policy.


Management of 三、一级 cache

(1) When the application invokes the session's Save (), update (), Savaeorupdate (), get () or load (), and the list (), iterate (), or

Filter () method, Hibernate will add the object to the first level cache if the corresponding object does not exist in the session cache. When you clean up the cache,

Hibernate synchronizes updates to the database based on the state of the objects in the cache. Session provides two ways to manage caching for your application: evict (Object obj)

: Clears the persisted object specified by the parameter from the cache. Clear (): Empties all persisted objects in the cache.

(2) Save, update, saveorupdate, load, list, iterate, lock will store data to the first level cache;

Save case://Add a student student student=new student (); Student.setname ("Small East"); S.save (student);//Put in a first cache//I immediately query student stu2= ( Student) S.get (Student.class, Student.getid ()); SelectSystem.out.println ("You just joined the student name is" +stu2.getname ());

(3) What operations will fetch data from a first-level cache : get, load, list

Get/load is first taken from the primary cache, if no . there are different operations. [Get will immediately send a request to the database, and load will return a proxy object until the user actually uses the data to send a request to the database ;

Check the number 45th student 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 see that query.list () query.uniueresut ( ) does not take data from the first level ! but query.list or Query.uniquerestu () the data will be stored to a level .

Attention:

①  first-level cache does not require configuration, you can use It has no protection mechanism in itself, so we programmers need to consider this question We can join   EVICT  or   clear to clear the Span style= "Font-family:times New Roman" >session objects in cache . EVICT  is to clear an object, clear sesion cache object

The life cycle of an object in the ②session cache , which is automatically destroyed when the session is closed .

③ we use HashMap to simulate a Session Cache, deepening the cache .

Iv. Management of Hibernate level two cache

1. The general process for Hibernate level two cache policy is as follows:

1) When a condition is queried, always issue a SELECT * FROM table_name where .... (select all fields) such SQL statements query the database and get all the data objects at once.

2) Put all the obtained data objects into the second level cache based on the ID.

3) When hibernate accesses the data object according to the ID, it is first checked from the session cache, and if the level two cache is configured, it is checked from the level two cache, and the database is not found, and the result is placed in the cache by ID.

4) Update the cache while deleting, updating, and adding data.

Hibernate level Two cache policy is a cache policy for ID queries and is not useful for conditional queries. To do this, Hibernate provides query Cache for conditional queries.

5) A level two cache object may be placed in memory, or it may be placed on a disk .


2. What kind of data is suitable for storage in the second level cache?

1) rarely modified data

2) data that is not very important, allowing occasional concurrent data to occur

3) data that will not be accessed concurrently

4) Reference data, refers to the supply of constant data reference, its limited number of instances, its instances will be referenced by many other instances of the class, the instance is rarely or never modified.

3. Not suitable for storing data in a second level cache?

1) Frequently modified data

2) financial data, never allow concurrency

3) data that is shared with other apps.

4. Common cache plug-in hibernater level two cache is a plug-in, here are a few common cache plugins:

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 for hibernate queries

The cache provides support.

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.


5. The main steps for configuring Hibernate level two cache:

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

2) Select the appropriate cache plug-in, and then edit the plugin's configuration file.

<property name= "Hbm2ddl.auto" >update</property><!--start level two cache--><property Name= "Cache.use_ Second_level_cache ">true</property><!--Specify which level of two cache to use--><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"/><!--specifies which domain enable level two cache specifically describes level two cache policy: 1. Read-only2. Read-write3. Nonstrict-read-write4. Transcational--><class-cache class= "com.hsp.domain.Student" usage= "Read-write"/>

3) you can put the oscache.properties file in src directory, so you can specify the objects that are placed in level two cache capacity size .  default +

6. Use level Two cache:

TODO auto-generated method stub//by getting a sesion, let Hibernate framework run (config-> load hibernate.cfg.xml) Session s=null; Transaction Tx=null;try {//We use the basic template to explain. S=hibernateutil.opensession (); tx=s.begintransaction ();//Query No. 45th student Student stu1= (Student) s.get (student.class);//45-> first-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 No. 45th Student 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 ();}} Complete a statistic that counts the information in the Sessfactory//sessionfactory object. Statistics statistics= hibernateutil.getsessionfactory (). getstatistICS (); SYSTEM.OUT.PRINTLN (statistics); System.out.println ("Put" +statistics.getsecondlevelcacheputcount ()); SYSTEM.OUT.PRINTLN ("hit" +statistics.getsecondlevelcachehitcount ()); System.out.println ("Miss" +statistics.getsecondlevelcachemisscount ());

After configuring the level two cache, please be aware that you can check your configuration hit rate is not high by Statistics



Hibernate cache and level two cache

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.