Hibernate level two cache, using Ehache cache framework

Source: Internet
Author: User
Tags commit stub jboss
1. Preface

A secondary cache is a cache mechanism that belongs to the sessionfactory level and is a process-wide cache. The first-level cache is the session-level cache, which is a transaction-scoped cache that is managed by hibernate and generally does not require intervention.

Hibernate supports the following third-party caching frameworks:

Read-only

Transactional

Cache Interface Supported Strategies
HashTable (testing only)  

read-only

Nontrict read-write

Read-write

   
EHCache  

Read-only

Nontrict read-write

Read-write

   
oscache  

read-only

Nontrict read-write

Read-write

   
swarmcache  

read-only

nontrict read-write

   
JBoss Cache 1.x  

read-only

Transac tional

   
JBoss Cache 2.x  

2. Download Third party Ehcache.jar

Ehcache.jar package, there are two kinds, one is Org.ehcache, the other is Net.sf.ehache. Hibernate is integrated with Net.sf.ehcache. So you should download Net.sf.ehcache. Hibernate is not supported if you are using the Org.ehcache jar package:

Download down the jar package, need to put in the project, in this case, is placed in the Webroot/web-inf/lib directory of the Sshwebproject project, it is important to note that Ehcache.jar package depends on Commons-logging.jar, you also have to see if you have Commons-logging.jar in the project.

3. Activate Hibernate's Level two cache

If you want to use the Hibernate.cfg.xml configuration file, it will cause the configuration to use a level two cache differently, generally because the project is integrated with the spring framework, so configure level two cache,

The following two cases are divided:

1) The project has Hibernate.cfg.xml

1-1) turn on Hibernate cache level two cache function

Modify Hibernate.cfg.xml to add the following:

	           <!--turn on level two cache, use Ehcache Cache--
		       <prop key= "Hibernate.cache.use_second_level_cache" >true</prop>
		       <prop key= "Hibernate.cache.provider_class" >org.hibernate.cache.EhCacheProvider</prop>

1-2) to configure which entity class objects need to be stored in level two cache, there are two ways

In this case, the Edu.po.Users user object as an example, the corresponding entity mapping file is Users.hbm.xml.

Mode one, configure in the Hibernate.cfg.xml file

		<!--to configure objects with level two cache
	    --<class-cache usage= "Read-write" class= "Edu.po.Users"/>  
		<!--Cache Collection Objects Example-
		<!--<collection-cache usage= "Read-write" collection= "Cn.itcast.domain.Customer.orders"/>-- >

Mode two, configured in the HBM file (Entity mapping file)

Users.hbm.xml, add the following:

        <cache usage= "Read-write"/>

2) After the spring framework is integrated, there is no HIBENATE.CFG.MLX file

1-1) turn on Hibernate cache level two cache function

Modify the Applicationcontext.xml file and add the following hibernateproperties to the Sessionfactory bean as follows:

	<bean id= "sessionfactory"
		class= "Org.springframework.orm.hibernate3.LocalSessionFactoryBean" >
		......
		<property name= "Hibernateproperties" >
		    <props> ...
	           <!--turn on level two cache, use Ehcache Cache--
		       <prop key= "Hibernate.cache.use_second_level_cache" >true</prop>
		       <prop key= "Hibernate.cache.provider_class" >org.hibernate.cache.EhCacheProvider</prop>
		       ......
		    </props>
		</property>
		<property name= "mappingresources" >
		    <list>
		       < value>edu/po/users.hbm.xml</value>
		       <value>edu/po/TLog.hbm.xml</value>
		    </list >
		</property>
	</bean>


1-2) Configure which entity class objects need to be stored in level two cache

In this case, the Edu.po.Users user object as an example, the corresponding entity mapping file is Users.hbm.xml.

Configuring in HBM Files (Entity mapping files)

Users.hbm.xml, add the following:

        <cache usage= "Read-write"/>
4. Configuring the Ehcache.xml file

Rename the Ehcache-failsafe.xml in the Ehcache.jar package to ehcache.xml into SRC, because hibernate defaults to find Classpath*:ehcache.xml

In this case, the <diskStore> and <defaultCache> are modified as follows

    <diskstore path= "D:/ehcachedata"/>

5. Demo

Springbeanutils.java:

Package utils;
Import Org.apache.log4j.Logger;
Import Org.hibernate.SessionFactory;
Import Org.springframework.context.ApplicationContext;

Import Org.springframework.context.support.FileSystemXmlApplicationContext; /** * Title:SpringBeanUtils.java * Description: Tool class to get spring Bean instance objects * @author Yh.zeng * @date 2017-6-27 */Public
	
	Class Springbeanutils {private static Logger Logger = Logger.getlogger (Springbeanutils.class);
	static String FilePath = "Webroot/web-inf/applicationcontext.xml";
	Static ApplicationContext CONTEXT;
		static{try{CONTEXT = new Filesystemxmlapplicationcontext (FilePath);
		}catch (Exception e) {logger.error (Stringutils.getexceptionmessage (e)); }}/** * Gets the unique identity of the bean * @param uniqueidentifier bean, either the ID or the name * @return */public static Object Getbea
	N (String uniqueidentifier) {return Context.getbean (uniqueidentifier); /** * Gets the unique identity of the Sessionfacotry object * @param uniqueidentifier sessionfactory bean, either an ID or a name * @rEturn */public static sessionfactory getsessionfactory (String uniqueidentifier) {return (sessionfactory) context.get
	Bean (uniqueidentifier);
	} public static String GetFilePath () {return filePath;
		public static void SetFilePath (String filePath) {springbeanutils.filepath = FilePath;
	CONTEXT = new Filesystemxmlapplicationcontext (FilePath);
 }
	
}

Hibernateehcachetest.java:

Note: The ability to query the cache and view the cache statistics needs to be configured separately, see blog Hibernate open Query cache, hibernate to turn on collection cache statistics

Package edu.test;
Import java.sql.SQLException;
Import org.hibernate.HibernateException;
Import Org.hibernate.Query;
Import org.hibernate.Session;
Import Org.hibernate.SessionFactory;
Import Org.hibernate.stat.EntityStatistics;
Import Org.hibernate.stat.Statistics;
Import Org.springframework.orm.hibernate3.HibernateCallback;
Import Org.springframework.orm.hibernate3.HibernateTemplate; Import Utils.
Springbeanutils;

Import Edu.po.Users; /** * Title:HibernateEhCacheTest.java * description:hibernate level two cache test * @author Yh.zeng * @date 2017-7-4 */Public CL hibernateehcachetest {static Sessionfactory sessionfactory = Springbeanutils.getsessionfactory ("SessionFactory")
	
    ; public static void Main (String args[]) {//session.get () method supports level two cache System.out.println ("############## #session. G
		ET () ############### ");
		Session Session1 = Sessionfactory.opensession ();
		Session1.begintransaction ();
		Users user1 = (users) session1.get (Users.class, 6); System.out.println ("User name:" + User1.getusername ());
		Session1.gettransaction (). commit ();

		Session1.close ();
		Session Session2 = Sessionfactory.opensession ();
		Session2.begintransaction ();
		Users user2 = (users) session2.get (Users.class, 6);
		System.out.println ("User name:" + user2.getusername ());
		Session2.gettransaction (). commit ();
		
		Session2.close ();
		The Query.list () method supports query cache System.out.println ("############## #Query. List () ###############");
		Session Session3 = Sessionfactory.opensession ();
		Session3.begintransaction ();
		Query query = Session3.createquery ("from Users where id =: id");
		Query.setparameter ("id", 6); Query.setcacheable (TRUE);
		Enable query caching Users User3 = (users) query.list (). get (0);
		System.out.println ("User name:" + user3.getusername ());
		Session3.gettransaction (). commit ();
		
		
		Session3.close ();
		Session session4 = Sessionfactory.opensession ();
		Session4.begintransaction ();
		Query Query2 = Session4.createquery ("from Users where id =: id");
		Query2.setparameter ("id", 6); Query2.setcacHeable (TRUE);
		Enable query caching Users User4 = (users) query2.list (). get (0);
		System.out.println ("User name:" + user4.getusername ());
		Session4.gettransaction (). commit ();
		
		Session4.close ();
		The Query.iterate () method does not support query cache System.out.println ("############## #Query. Iterate () ###############");
		Session session5 = Sessionfactory.opensession ();
		Session5.begintransaction ();
		Query Query3 = Session5.createquery ("from Users where id =: id");
		Query3.setparameter ("id", 6); Query3.setcacheable (TRUE);
		Enable query caching for users USER5 = (users) query3.iterate (). Next ();
		System.out.println ("User name:" + user5.getusername ());
		Session5.gettransaction (). commit ();
		
		Session5.close ();
		Session session6 = Sessionfactory.opensession ();
		Session6.begintransaction ();
		Query Query4 = Session6.createquery ("from Users where id =: id");
		Query4.setparameter ("id", 6); Query4.setcacheable (TRUE);
		Enable query caching for users USER6 = (users) query4.iterate (). Next ();
		System.out.println ("User name:" + user6.getusername ()); Session6.gettRansaction (). commit ();
		
		Session6.close ();
		The Session.load () method supports level two cache System.out.println ("############## #Session. Load () ###############");
		Session session7 = Sessionfactory.opensession ();
		Session7.begintransaction ();
		Users User7 = (users) session7.load (Users.class, 6);
		System.out.println ("User name:" + user7.getusername ());
		
		Session7.gettransaction (). commit ();
		Session session8 = Sessionfactory.opensession ();
		Session8.begintransaction ();
		Users User8 = (users) session8.load (Users.class, 6);
		System.out.println ("User name:" + user8.getusername ());
		
		Session8.gettransaction (). commit ();
		Hibernatetemplate.find supports query cache System.out.println ("############## #HibernateTemplate. Find () ###############");
		Hibernatetemplate hibernatetemplate = new Hibernatetemplate (sessionfactory); Hibernatetemplate.setcachequeries (TRUE);
		Open Query Cache Users User9 = (users) hibernatetemplate.find ("from Users where id =?", 6). Get (0);
		
		System.out.println ("User name:" + user9.getusername ()); HibernateTemplate hibernateTemplate2 = new Hibernatetemplate (sessionfactory); Hibernatetemplate2.setcachequeries (TRUE);
		Open Query Cache Users USER10 = (users) hibernatetemplate2.find ("from Users where id =?", 6). Get (0);
		
		System.out.println ("User name:" + user10.getusername ()); Hibernatetemplate.execute supports query cache System.out.println ("############## #HibernateTemplate. Execute () ###############
	    ");
		Hibernatetemplate hibernateTemplate3 = new Hibernatetemplate (sessionfactory); Hibernatetemplate3.setcachequeries (TRUE); Open Query Cache users User11 = Hibernatetemplate3.execute (new hibernatecallback<users> () {@Override public Users D Oinhibernate (Session session) throws Hibernateexception, SQLException {//TODO auto-generated method stub Qu
				ery query = Session.createquery ("from Users where id =: id");
				Query.setparameter ("id", 6);
			Return (Users) query.list (). get (0);
		}
		});
		
		System.out.println ("User name:" + user11.getusername ()); Hibernatetemplate hibernateTemplate4 = NEW hibernatetemplate (Sessionfactory); Hibernatetemplate4.setcachequeries (TRUE); Open Query Cache users user12 = Hibernatetemplate4.execute (new hibernatecallback<users> () {@Override public Users D Oinhibernate (Session session) throws Hibernateexception, SQLException {//TODO auto-generated method stub Qu
				ery query = Session.createquery ("from Users where id =: id");
				Query.setparameter ("id", 6);
			Return (Users) query.list (). get (0);
		}
		});
		
		System.out.println ("User name:" + user12.getusername ());
		Cache statistics Statistics statistics= sessionfactory.getstatistics ();
		SYSTEM.OUT.PRINTLN (statistics);
		System.out.println ("Put" +statistics.getsecondlevelcacheputcount ());
		SYSTEM.OUT.PRINTLN ("hit" +statistics.getsecondlevelcachehitcount ());
		System.out.println ("Miss" +statistics.getsecondlevelcachemisscount ()); Detailed cache statistics for (int i = 0; i < statistics.getentitynames (). length; i++) {String entityname = Statistics.geten
			Titynames () [i]; Entitystatistics Entitystatistics = Statistics.getentitystatistics (entityname);
			StringBuilder cacheoperator = new StringBuilder (); Cacheoperator.append ("CategoryName:"). Append (Entitystatistics.getcategoryname ()). Append (", DeleteCount:") . Append (Entitystatistics.getdeletecount ()). Append (", Fetchcount:"). Append (Entitystatistics.getfetchcount () ). Append (", Insertcount:"). Append (Entitystatistics.getinsertcount ()). Append (", Loadcount:" ). Append (Entitystatistics.getloadcount ()). Append (", Optimisticfailurecount:"). Append (entit Ystatistics.getoptimisticfailurecount ()). Append (", Updatecount:"). Append (Entitystatistics.getupdatecount (			             
			));
		System.out.println (Cacheoperator.tostring ()); }
	}
}


Item Demo:https://github.com/zengyh/sshwebproject.git

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.