We know that the first level of hibernate caching is to cache the data in the session to reduce the interaction with the database. What about the level two cache?
First, the application situation
For example, in the 12306 purchase of tickets, you need to choose the origin and destination, if each point with the database once, it is not appropriate, these location data for a long period of time will not change (Shandong province for a long time is called Shandong Province), so should be cached up, It is not necessary to interact with the database every time, and this type of data security is not very high.
Data for Level two cache:
In modern software development, there is a kind of data does not have any private, for the public data, the data is basically unchanged, the data confidentiality is not very strong, but will often be used (such as train tickets on the origin and destination data).
Note: If a data is constantly changing, it is not suitable for caching.
Streaming data: Data is constantly changing data, such as mobile phone applications to obtain the location of the mobile phone, backstage push system, send some information, such as text message will indicate your night traffic more than how much, it is recommended to buy night traffic. This type of data is suitable for use with Strom.
Second, life cycle
The second-level cache is a sessionfactory-level cache whose life cycle and sessionfactory are consistent, and hibernate is enabled.
The location of the second-level cache in Hibernate
Therefore, hibernate does not implement a level two cache, but instead uses a third-party plug-in to implement level two caching.
Settings for 三、二级 Cache
Leverage a level two cache implemented by Ehcache
1. Add the jar package required for Ehcache
2. Configure in Hibernate configuration file
四、二级 Cached operations
Which methods can put objects into the level two cache?
Get method, the list method can put one or some objects into the level two cache
What methods can be used to extract objects from the level two cache?
Get method, the iterator method can extract
Note: Use of the time must be careful using each method, when fetching data, if the list used as a iterate will result in efficiency and its reduction
storage policies for 五、二级 cache
Read-only: objects can only be read and cannot be modified as long as they are loaded into level two cache.
Read-write: The ability to read and write to objects in the level two cache
Note: generally set to Read-only
Cache gets Disk
If the privilege of a system is particularly large, this is not suitable for a long time into the level two cache, will lead to the memory gradually become larger, the query efficiency is gradually reduced, this situation can be moved to disk level two cache, but in modern development if you need more cache, generally use distributed cache.
Test:
Hibernate.cfg.xml
<?xml version= ' 1.0 ' encoding= ' utf-8 '? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://hibernate. Sourceforge.net/hibernate-configuration-3.0.dtd ">Classes
public class Classes implements Serializable{private Long cid;private String name;private set<student> students;}
Classes.hbm.xml
<class name= "Classes" table= "Classes" ><cache usage= "Read-write"/><!--read-only--><id name= "CID" > <generator class= "native" ></generator></id><property name= "name" ></property>< Set name= "Students" cascade= "Save-update" inverse= "true" ><cache usage= "read-only"/><!--set the two-level cache of the collection- <!--key: Foreign key, tell hibernate to establish the relationship between classes and student through CID--><key column= "CID" ></key><one-to-many class= "Student"/></set></class>
Student
public class Student implements Serializable{private Long sid;private String name;private Classes Classes;}
Student.hbm.xml
<class name= "Student" table= "Student" ><id name= "Sid" ><generator class= "native" ></generator ></id><property name= "name" ></property><many-to-one cascade= "Save-update" name= "classes" column= "CID" class= "Classes" ></many-to-one></class>
Test class
public class Sessionfactorycachetest {private Session session;private Transaction transaction;private sessionfactory sessionfactory;/** * Test GET, after the session is closed, request again, do not issue SQL * This method when fetching data, first from the primary cache, if the level two cache is turned on, then from the level two cache, no, then check the database * You can see clearly in the Defaultloadeventlistener.class * 440 rows: From the first level cache, 459 rows: From the two cache, 477 rows: from the database * Get can put the object into the two cache, you can also fetch data from the level two cache */@Testpub LIC void Testget () {sessionfactory = Hibernateutils.getsessionfactory (); session = Hibernateutils.opensession (); Classes Classes = (Classes) session.get (Classes.class, 1L); System.out.println (Sessionfactory.getstatistics (). Getentityloadcount ());//1session.close (); session = Hibernateutils.opensession (); Classes = (classes) session.get (Classes.class, 1L);//Do not emit sqlsession.close ();} /** * Hibernate provides a statistical mechanism for level two caching * Save cannot deposit objects in level two cache */@Testpublic void Testsave () {sessionfactory = Hibernateutils.getsessionfactory (); session = Hibernateutils.opensession (); transaction = Session.begintransaction () ; Classes Classes = new Classes () Classes.setname ("a"); Session.save (CLASSEs); System.out.println (Sessionfactory.getstatistics (). Getentityloadcount ());//0transaction.commit (); Session.close ( );} /** * Session.update does not operate level two cache */@Testpublic void Testupdate () {sessionfactory = Hibernateutils.getsessionfactory (); Session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); Classes Classes = new Classes () classes.setcid (3L); Classes.setname ("AfDs"); Session.update (Classes); System.out.println (Sessionfactory.getstatistics (). Getentityinsertcount ());//0transaction.commit ();//Will error, but not affect, Set to <cache usage= "Read-write", if the collection is also set to a level two cache, the set should also be the same session.close ();} /** * HQL list, you can put the object into the level two cache, but not from the level two cache data */@Testpublic void Testquerylist () {sessionfactory = Hibernateutils.getsessionfactory (); session = Sessionfactory.opensession (); Session.createquery ("From Classes"). List (); System.out.println (Sessionfactory.getstatistics (). Getentityloadcount ());//Not 0session.close (); session = Sessionfactory.opensession (); Session.createquery ("From Classes"). List ();//Issue SqL, because Getentityloadcount is not 0, the list () can put the object into a level two cache, but cannot take the object from the two-level cache Session.close ();} /** * Iterator, can fetch data from the level two cache * Iterate method query strategy: * First Find all the ID values in the table and then find the object from the two cache based on the ID value, and if so, take advantage of the level two cache, * if not, query the value of all properties by ID */@Testpublic void Testqueryiterate () {sessionfactory = Hibernateutils.getsessionfactory (); session = Sessionfactory.opensession (); Session.createquery ("From Classes"). List (); System.out.println (Sessionfactory.getstatistics (). Getentityloadcount ());//Not 0session.close (); session = Sessionfactory.opensession ();iterator<classes> Iterator = Session.createquery ("from Classes"). Iterate (); while (Iterator.hasnext ()) {Classes Classes = (Classes) iterator.next (); System.out.println (Classes.getname ());} Session.close ();} /** * Collection of level two caches that need to be set in the Hbm.xml file * The collection has a level cache and a level two cache */@Testpublic void testcollection () {sessionfactory = Hibernateutils.getsessionfactory (); session = Sessionfactory.opensession (); Classes Classes = (Classes) session.get (Classes.class, 1L); set<student> students = classes.getstudents (); for (Student student:students) {System.out.println (Student.getname ());} System.out.println (Sessionfactory.getstatistics (). Getcollectionloadcount ());//1session.close (); /** * Level two cache to disk */@Testpublic void Testcachedisk () {sessionfactory = Hibernateutils.getsessionfactory (); session = Sessionf Actory.opensession (); Session.createquery ("From Classes"). List (); try {thread.sleep (2000L);//stop for a while or write no data} catch ( Exception e) {e.printstacktrace ();} Session.close ();}}
Second-level cache enterprise application is not much, really some chicken Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Hibernate learning Note (vi)-hibernate's level two cache