Hibernate-level cache and level two cache use the detailed explanation __ cache

Source: Internet
Author: User
Tags object object sesion
conceptual interpretation of 一、一级 cache level two cache

(1) First-level caching is the session-level cache, a session to do a query operation, it will put the results of this operation in a cache, if the short 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 caching, as the name suggests, is the query will be the query results cache to the level two cache, if the same sessionfactory

A session that is created performs the same operation, and the hibernate will take the result from the level two cache and no longer connect to the database;

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

, usually without intervention; the second level of caching is the sessionfactory level cache, which is a process-scoped or cluster-wide cache. At this level, other slow

Save can be configured and changed, and can be dynamically loaded and unloaded. Hibernate also provides a query cache for query results that relies on second-level caching; comparison of 二、一级 cache and level two cache

(1) The first level cache the second level cache holds the form of data. The scope transaction scope of the bulk data cache of the persisted object object, each with a separate first level

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

Concurrency problems occur without the need to provide concurrent access policies because multiple transactions simultaneously access the same data in the secondary cache, you must provide an appropriate concurrency access policy to protect

Certificate-specific transaction isolation level data expiration policy does not provide a data expiration policy.

(2) objects in the first cache will 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, the longest time allowed for the object to be cached, and the allowed object to

The maximum amount of free time in the cache physical storage media memory 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 a number

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

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

Implementation is provided by a third party, hibernate only provides a caching adapter (Cacheprovider). Used to integrate specific cache plug-ins into the hibernate.

(5) How caching is enabled

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

The data in is copied to the cache as an object, and if you do not want to enable the first level cache for bulk update and bulk Delete operations, you can bypass the hibernate API and directly

The JDBC API is used to perform the operation of the reference.

(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 often read but rarely modified, it

You may consider using a second level cache.

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

How users manage caching the physical media for the first level of caching is memory, and due to the limited memory capacity, the number of loaded objects must be restricted by appropriate retrieval policies and retrieval.

The Evit () method of the session can explicitly empty a specific object in the cache, but this method is not recommended. The second level of cache physical media can be memory and hard drive, so the second

A level cache can hold a large amount of data, and the Maxelementsinmemory property value of the data expiration policy can control the number of objects in memory.

(8) Management of the second level of caching mainly includes two aspects: Select the persistence class that needs to use the second level cache, set the appropriate concurrency access policy: Select the cache adapter, set the appropriate data expiration policy. Management of 三、一级 caching

(1) When the application calls save (), update (), Savaeorupdate (), get (), or load () of the session, and the list (), iterate (), or

Filter () method, if the corresponding object does not exist in the session cache, Hibernate adds the object to the first level cache. When the cache is cleaned,

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

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

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

Save case:
	//Add a student
			Student student=new Student ();
			Student.setname ("small East");

			S.save (student);//Add first cache

			//I will immediately query
			student stu2= (student) S.get (Student.class, Student.getid ());//select
			System.out.println ("The name of the student you just joined" is "+stu2.getname");

(3) What operation will be cached from the first level of data: Get, load, list

The get/load will first be fetched from the primary cache, if not. There are different operations [get will immediately send a request to the database, and load will return a proxy object, until the user really to use the data, will send a request to the database;

Query number 45th students

			Student stu= (Student) s.get (Student.class,);

			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 slow down the data from the first level! But query.list or Query.uniquerestu () will hold the data to a level of ease.

Attention:

①-level caching does not need to be configured, it can be used, it does not have a protection mechanism, so we programmers to consider this problem, we can with evict or clear to clean up the session cache objects. Evict is to clear an object, clear is to erase all sesion cached objects

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

③ we use HashMap to simulate a session cache, deepen the cache depth. Iv. Management of Hibernate level two cache

1. The general process of Hibernate level two caching strategy is as follows:

1 when the 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 All the data objects obtained are put into the second level cache according to the ID.

3 when hibernate according to ID access to data objects, first from the session-level cache, check, if configured with a level two cache, then from the level two cache, check, and then query the database, the results in accordance with the ID into the cache.

4 when deleting, updating, and adding data, update the cache at the same time.

The hibernate level two cache policy is for the cache policy for the ID query and has no effect on the conditional query. To do this, Hibernate provides query Cache for conditional queries.

5 The object of level two cache may be placed in memory, or it may be placed on disk.

2. What data is suitable for storage in the secondary cache.

1 data that is rarely modified

2) is not very important data, allowing occasional concurrent data

3 data that will not be accessed concurrently

4 reference data, refers to the supply of reference to the constant data, its number of instances are limited, its instances are referenced by many other classes of instances, the instance is very few or never be modified.

3. Data not suitable for storage to the second level of caching.

1 data that is often modified

2 financial data, the absolute not allowed to appear concurrent

3 data that is shared with other applications.

4. Commonly used cache Plug-ins Hibernater level two cache is a plug-in, the following are several commonly used cache Plug-ins:

Ehcache: As a process-wide cache, the physical media that holds the data can be either memory or a hard disk, providing support for the Hibernate query cache.

Oscache: Can be a process-wide cache, the physical media that holds the data can be memory or hard disk, provides a rich cache data expiration policy, queries against hibernate

Caching provides support.

Swarmcache: can serve as a cluster-wide cache, but does not support hibernate query caching.

Jbosscache: Serves as a cluster-wide cache, supports transactional concurrency access policies, and provides support for hibernate query caching.

5. The main steps to configure the Hibernate level two cache:

1 Select the persistent class that needs to use level two caching to set its concurrent access policy for the named cache. This is the most worthy step to consider seriously.

2 Select the appropriate cache plug-in, and then edit the plug-in'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 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"/>
	<!-- Specify which domain enables level two caching 
	special description level Two cache policy:
	1 read-only
	2 read-write
	3 nonstrict-read-write
	4. Transcational
	-->
	<class-cache usage= "Read-write"/>

3 The Oscache.properties file can be placed in the SRC directory, so you can specify the capacity size of the object to be placed in level two cache. Default 1000

6. Use level Two cache:

TODO auto-generated Method Stub//by getting a sesion, let the hibernate frame run (config-> load hibernate.cfg.xml) session s=null;

		Transaction Tx=null;
			try {//We use the base template to explain.
			S=hibernateutil.opensession ();

			Tx=s.begintransaction ();

			Query number 45th students Student stu1= (Student) s.get Student.class (;//45->) (System.out.println ());

		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 base 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 statistical, statistical information on 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 ());

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.