In many projects, also used to the hibernate level two cache, now learn how to use the two cache in the Hibernate, the first to add the following configuration information to the corresponding location in the Beans.xml:
Hibernate.cache.use_second_level_cache=true
Hibernate.cache.use_query_cache=false
Hibernate.cache.provider_class=org.hibernate.cache.ehcacheprovider
Beans.xml
<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-2.5.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context /spring-context-2.5.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-2.5.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-2.5.xsd "> <context:annotation-config/> <bean id=" DataSource "class=" Org.apache.commons.dbcp.BasicDataSource "destroy-method=" Close "> <property name=" driverclassname "value=" Org.gjt.mm.mysql.Driver "/> <propertY name= "url" value= "Jdbc:mysql://localhost:3306/springjdbc?useunicode=true&characterencoding=utf-8"/> < Property name= "username" value= "root"/> <property name= "password" value= "456"/> <!--the initial value of the connection pool startup--> < Property Name= "InitialSize" value= "1"/> <!--the maximum connection pool--> <property name= "maxactive" value= ""/> -Maximum idle value. After a peak time, the connection pool can slowly release a part of the connection that has not been used, and has been reduced to maxidle until--> <property name= "Maxidle" value= "2"/> <!-- Minimum idle value. When the number of idle connections is less than the threshold, the connection pool will advance to some connections to avoid the flood peak when it is too late to apply--> <property name= "Minidle" value= "1"/> </bean> <!-- This configuration allows you to define a Sessionfactory object that exists only in a container, which is a single instance of the form--> <bean id= "sessionfactory" class= " Org.springframework.orm.hibernate3.LocalSessionFactoryBean "> <property name=" dataSource "ref=" DataSource " > <!--data source--> <property name= "mappingresources" > <list> <value>cn/itcast/bean/ person.hbm.xml</value><!--Entity Bean Mapping metadata--> </list> </property> <property name= "hIbernateproperties "> <value> hibernate.dialect=org.hibernate.dialect.mysql5dialect hibernate.hbm2ddl.auto=update<!--representative or not to generate database table structure based on mapped metadata--> Hibernate.show_sql=false <!-- Whether to print hibernate executed sql--> Hibernate.format_sql=false <!--If you want to format it--> <!--These two are useful primarily in the testing phase--> <!-- Represents the use of Hibernate level two cache--> Hibernate.cache.use_second_level_cache=true <!--represents whether or not to use query caching, which is not used here because the query cache does not have a high hit rate , so we don't have to cache its data for every user's query, so this is set to False--> Hibernate.cache.use_query_cache=false <!--used to specify a driver class that uses a cache product--> Hibernate.cache.provider_class=org.hibernate.cache.ehcacheprovider </value> </property> </bean> <!--configuration transaction management, the transaction manager used is provided by spring for us, a transaction manager--> <!--for hibernate As long as the session created through the Sessionfactory object is included in the transaction manager--> <bean id= "Txmanager" Org.springframework.orm.hibernate3.HibernateTransactionManager "> <property name=" sessionfactory "ref=" Sessionfactory "/> </bean> <!--configuration transactions are declared in two ways: 1 are xml-based and 1 are based on annotations, where annotations are used to declare a transaction--> <!--This opens up support for @transaction annotations, and the transaction manager used here is the txmanager--> <tx:annotation-driven mentioned earlier Transaction-manager = "Txmanager"/> <bean id= "Personservice" class= "Cn.itcast.service.impl.PersonServiceBean"/> </beans>
Ehcache This cache product is to be used in a jar file that is under the Hibernate Core installation package: lib/optional/ Ehcache-1.2.3.jar,ehcache can be defined under a configuration file, Ehcache the default profile ehcache.xml (placed under the classpath)
<?xml version= "1.0" encoding= "UTF-8"?> <!--defaultcache node is the default cache policy maxelementsinmemory the maximum allowable number of objects in memory Eternal set whether an object in the cache never expires Overflowtodisk the overflow object to the hard drive (when the object reaches 1000, will overflow "such as 1001" on the Hard Drive) timetoidleseconds Specifies how long the cached object is idle and expires, and the expired object is purged timetoliveseconds specifies the total surviving time of the cached object diskpersistent Whether the object is persisted when the JVM ends (whether the cached object is persisted to disk when the cache application shuts down). Diskexpirythreadintervalseconds Specifies the polling time--> <ehcache> <diskstore path= "D:/cache" for the listener thread that is specifically used to purge expired objects/> <!--the cached object exists under which path of the hard disk--> <!--Defaultcache defines some of the default behavior of the cache--> <defaultcache maxelementsinmemory= "1000" Eternal= "false" overflowtodisk= "true" timetoidleseconds= "timetoliveseconds=" "180" diskpersistent= "false" Diskexpirythreadintervalseconds= "/>" </ehcache>
This is the default configuration of the cache, and once this cache is configured, it can be applied to the entity beans in the hibernate, and we add a cache configuration inside the mapping metadata configuration of the entity bean that needs to be cached.
Person.hbm.xml
<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">
In this way, we can cache the person entity Bean application, and of course we can define some of its special caching settings for Cn.itcast.bean.Person this cache domain, and if not, use the < in Ehcache.xml as a default. Defaultcache/> caching policy. If you have a special caching setting, you can define it
Ehcache.xml
<?xml version= "1.0" encoding= "UTF-8"?> <!--defaultcache node is the default cache policy maxelementsinmemory the maximum allowable number of objects in memory Eternal set whether an object in the cache never expires Overflowtodisk the overflow object to the hard drive (when the object reaches 1000, will overflow "such as 1001" on the Hard Drive) timetoidleseconds Specifies how long the cached object is idle and expires, and the expired object is purged timetoliveseconds specifies the total surviving time of the cached object diskpersistent when the JVM ends is persisted (whether the cached object is persisted to disk when the cache application closes). Diskexpirythreadintervalseconds Specifies the polling time--> <ehcache> <diskstore path= "D:/cache" for the listener thread that is specifically used to purge expired objects/> <!--the cached object exists under which path of the hard disk--> <!--Defaultcache defines some of the default behavior of the cache--> <defaultcache maxelementsinmemory= "1000" Eternal= "false" overflowtodisk= "true" timetoidleseconds= "timetoliveseconds=" "180" diskpersistent= "false" Diskexpirythreadintervalseconds= "/>" <cache name= Cn.itcast.bean.Person "maxelementsinmemory=" eternal = "false" overflowtodisk= "true" timetoidleseconds= "timetoliveseconds=" diskpersistent= "false"/> </ Ehcache>
Now that caching is applied to the person entity, how do we test the cache on its current application? The caching on our application can be this: if, once the object of an ID is in the cache, it will not fetch the data from the database when it asks for the object of the same ID for the second time, and it gets the cached object from the memory. Based on this, we can test whether the cache is working.
Our plan is this.
Getperson (1)
//... Turn the database off
Getperson (1)
Getperson (1), call the business Bean's Getperson (1) method to get the first record, and the level two cache will put the record in the cache, that is, When we get the 1 person again the second time, it gets from the memory, not from the database.
Since the second fetch is obtained from memory, that is, we turn the database off in the middle, and when the second Getperson (1) Acquires the 1 person, if it can get it, it proves that the object was retrieved from memory because the database is already closed. Let's do an experiment now.
Personservicetest.java
package junit.test; Import java.util.List; Import Org.junit.BeforeClass; Import Org.junit.Test; Import Org.springframework.context.ApplicationContext; Import Org.springframework.context.support.ClassPathXmlApplicationContext; Import Cn.itcast.bean.Person; Import Cn.itcast.service.PersonService; public class Personservicetest {private static personservice personservice; @BeforeClass// This method is performed when the unit test Personservicetest instance is constructed//can be done in this method with some initialization operations public static void Setupbeforeclass () throws Exception { try {applicationcontext applicationcontext = new Classpathxmlapplicationcontext ("Beans.xml"); PersonService = ( Personservice) Applicationcontext.getbean ("Personservice"); catch (RuntimeException e) {e.printstacktrace ();}} ... @Test public void Testgetperson () {Person of person = Personservice.getperson (2). \ .... ()----------------- ); System.out.println (Person.getname ()); try {System.out.println ("Please close Database"); Thread.Sleep (15*1000); catch (Interruptedexception e) {E.prinTstacktrace (); } System.out.println ("Second start Acquisition"); person = Personservice.getperson (2); System.out.println (Person.getname ()); } ......................................... }
This experiment is mainly to prove that: when the database is closed, we go to get Person2 records, if it can return and correctly print information, it proves that this data is obtained from the cache (memory) to this object, not from the database to get the object, the database person table as shown:
The first thing to clear the D:/cache data, execute the unit test code of the Testgetperson () method, which is to manually close the MySQL database, the console print:
John doe
Please close the database
The second time to start getting
John doe
Note: In the case of our database shutdown, it can also obtain the person name, which proves that the object was obtained from the cache.
The application of our level two cache has been successful. Second-level caching in the enterprise is also a large number of use, so we have to master.
The section code here: Configure level Two caching for spring-integrated hibernate. zip