The second level cache is a process or cluster-wide cache that can be shared by all sessions
Secondary cache is a configurable plug-in
01. Configuration Use of Level two cache (Ehcache cache)
* * Introduce the following jar package.
Ehcache-1.2.3.jar Core Library
Backport-util-concurrent.jar
Commons-logging.jar
Configure Hibernate.cfg.xml to turn on level two caching
<property name= "Hibernate.cache.use_second_level_cache" >true</property>
Configure a two-level cache vendor
<property name= "Hibernate.cache.provider_class" >org.hibernate.cache.EhCacheProvider</property>
Configuring in a large configuration file (Hibernate.cfg.xml)
<class-cache usage= "Read-write" class= "cn.happy.entity.Student"/><collection-cache usage= " Read-write "collection=" "/>
The second-level cache holds the data principle:
Second-level cache testing:
/** * Test level Two cache * /@Test public void Testbulk () { //Get the data like session session = Hibernateutil.getsession (); Transaction tx=session.begintransaction (); Dept Dept = (Dept) session.get (dept.class,1); System.out.println (Dept.getdeptname ()); Tx.commit (); Hibernateutil.closesession (); System.out.println ("==========================="); SQL statements are not displayed because there is a level two cache Session session2 = hibernateutil.getsession (); Transaction tx2=session2.begintransaction (); Dept dept2 = (Dept) session2.get (dept.class,1); System.out.println (Dept2.getdeptname ()); Tx2.commit (); Hibernateutil.closesession (); }
Operation Result:
Because there is a level two cache, it is the query department name, so the second query does not display the SQL statement
To test the query cache:
List () method
/** * * * * */ @Test public void Testcache () { session=hibernateutil.getsession (); Transaction tx=session.begintransaction (); Query query = Session.createquery ("from Emp"); List () can only put data can not be removed list<emp> List = Query.list (); for (Emp emp:list) { System.out.println (Emp.getempname ()); } System.out.println ("================================"); Do not display sql: The previous step has been placed in level two cache list<emp> list1 = Query.list (); for (Emp emp:list1) { System.out.println (Emp.getempname ()); } System.out.println ("================================"); }
Run results
First put the data, the list () method can only put into the data, cannot take out the data, so when the query statement, the display of two SQL statements, which shows that the IST () method can only put data, cannot take out data, memory address is different, so display two SQL statements
Iterate () method
Operation Result:
The iterate () method can fetch the data, run the query statement, display two SQL, but these two SQL is not the same, confirming the iterate () method can take out the data
Second-level caching and configuration principles