Hibernate (12) session cache and level two cache

Source: Internet
Author: User

The primary role of a first-level cache is to manage objects.
Application-level caching (cache at the sessionfactory level), also known as Level two cache, is not enabled by default.

Whether it is a first-level cache or a level two cache, it is only valid to get objects based on the OID.

Package Test.hibernate.hbmsecondcache;import Java.util.hashset;import Java.util.set;public class Department {private Integer id;private String name;private set<employee> employees = new hashset<employee> ();p ublic integer GetId () {return ID;} public void SetId (Integer id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public set<employee> GetEmployees () {return employees;} public void Setemployees (set<employee> employees) {this.employees = employees;} @Overridepublic String toString () {//TODO auto-generated method Stubreturn "[employee:id=" + ID + ", name=" + name + "]";} }


Package Test.hibernate.hbmsecondcache;public class Employee {private Integer id;private String name;private Department Department = new Department ();p ublic Integer getId () {return ID;} public void SetId (Integer id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public Department getdepartment () {return Department;} public void Setdepartment (Department Department) {this.department = Department;} @Overridepublic String toString () {//TODO auto-generated method Stubreturn "[employee:id=" + ID + ", name=" + name + "]";} }


<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping public        "-//hibernate/hibernate mapping DTD 3.0//en"        "http// Hibernate.sourceforge.net/hibernate-mapping-3.0.dtd ">

<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping public        "-//hibernate/hibernate mapping DTD 3.0//en"        "http// Hibernate.sourceforge.net/hibernate-mapping-3.0.dtd ">


<! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http://www.hibernate.org/ Dtd/hibernate-configuration-3.0.dtd ">

The collection (employee) in lazy-loaded classes (Department) is also required to be lazy-loaded, while the employee class is opened.
Package Test.hibernate.hbmsecondcache;import Java.util.arraylist;import Java.util.iterator;import java.util.List; Import Org.hibernate.query;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Org.hibernate.cfg.configuration;import Org.junit.test;public class App {private static sessionfactory Sessionfactory = New Configuration ()//.configure ()//.addclass (Department.class)//Add Hibernate entity class (load corresponding mapping file). addclass ( Employee.class)//.buildsessionfactory ()//Get to the department associated employee @testpublic Void TestSessionCache1 () throws Exception {//------ ----------Test a second session-------------------session Session1 = Sessionfactory.opensession (); Session1.begintransaction (); Employee Employee1 = (employee) session1.get (Employee.class, 1); Session1.gettransaction (). commit (); Session1.close () ;//----------------Test the second session-------------------session Session2 = Sessionfactory.opensession (); Session2.begintransaction (); Employee Employee2 = (employee) session2.get (Employee.class, 1);//Employee2.setname ("Li Pu"); seSsion2.gettransaction (). commit (); Session2.close ();} @Testpublic void TestSessionCache2 () throws Exception {//----------------test the second session-------------------session Session1 = Sessionfactory.opensession (); Session1.begintransaction ();D epartment department1 = (Department) Session1.get (Department.class, 1); System.out.println (Department1.getemployees ()); Session1.gettransaction (). commit (); Session1.close ();//--------- -------Test the second session-------------------session Session2 = Sessionfactory.opensession (); Session2.begintransaction () ;D epartment Department2 = (Department) session2.get (Department.class, 1);//Department2.setname ("Research and Development department"); System.out.println (Department2.getemployees ()); Session2.gettransaction (). commit (); Session2.close ();} Query.list () default does not use level two cache @testpublic void Testquerycache () throws Exception {//----------------------------------- Session Session1 = Sessionfactory.opensession (); Session1.begintransaction (); list<employee> list = Session1.createquery ("from Employee e WHERE e.id&lT;5 "). List (); SYSTEM.OUT.PRINTLN (list); Session1.gettransaction (). commit (); Session1.close ();//------------------------------- --------------------Session session2 = sessionfactory.opensession (); Session2.begintransaction (); List<employee> List2 = Session2.createquery ("from Employee e WHERE e.id<5"). List (); System.out.println (List2); Session2.gettransaction (). commit (); Session2.close ();} /* When querying using the Hql method, the cache is used if the iterator () method is used. This method first queries all eligible ID collections, and then one by one to find the data by ID. * But this method will have n+1 query problems, improve performance is limited, less common. */@Testpublic void TestQueryCache2 () throws Exception {//-----------------------------------Session Session1 = Sessionfactory.opensession (); Session1.begintransaction ();iterator<employee> Iterator1 = Session1.createquery ("From Employee WHERE ID <5"). Iterate (), while (Iterator1.hasnext ()) {System.out.println ( Iterator1.next ());} Session1.gettransaction (). commit (); Session1.close ();//--------------------------------------------------- Session Session2 = Sessionfactory.opensession (); Session2.begIntransaction ();iterator<employee> Iterator2 = Session2.createquery ("From Employee WHERE ID <5"). Iterate (); while (Iterator2.hasnext ()) {System.out.println (Iterator2.next ());} Session2.gettransaction (). commit (); Session2.close ();} Use a level two cache to open the query cache in the main profile @testpublic void TestQueryCache3 () throws Exception {//----------------------------------- Session Session1 = Sessionfactory.opensession (); Session1.begintransaction (); list<employee> list = Session1.createquery ("from Employee e WHERE e.id<5")//.setcacheable (True)//.list (); SYSTEM.OUT.PRINTLN (list); Session1.gettransaction (). commit (); Session1.close ();//------------------------------- --------------------Session session2 = sessionfactory.opensession (); session2.begintransaction ();// Two query conditions need the same level two cache only with list<employee> List2 = session2.createquery (//"from Employee e WHERE e.id<5")//.setcacheable (true)//.list (); System.out.println (List2); Session2.gettransaction (). commit (); Session2.close ();} @Testpublic void TESTUPDATETIMESTAMPCACHe () throws Exception {//-----------------------------------Session Session1 = Sessionfactory.opensession (); Session1.begintransaction (); list<employee> list = Session1.createquery ("from Employee e WHERE e.id<2")//.setcacheable (True)//.list (); Session1.createquery ("UPDATE Employee SET name=?") WHERE id=? "). Setparameter (0, "comics")//.setparameter (1, 3)//.executeupdate (); SYSTEM.OUT.PRINTLN (list); Session1.gettransaction (). commit (); Session1.close ();//------------------------------- --------------System.out.println ("============================="); Session Session2 = Sessionfactory.opensession (); session2.begintransaction ();//Two query conditions require the same level two cache to be used List<employee > list2 = session2.createquery (//"from Employee e WHERE e.id<7")//.setcacheable (True)//.list ();//Break point->debug, You can see the e:/cache/cache generated file//At this time employees[3] has expired, will output Session1 updated results System.out.println (LIST2); Session2.gettransaction (). Commit (); Session2.close ();}}
You need to configure Ehcache.xml with Encache cache. Import some jar packages: Ehcache-1.5.0.jar, Backport-util-concurrent.jar, Commons-logging-1.0.4.jar

<ehcache> <!--cache file Location--<diskstore path= "e:/cache/"/> <!--Default cache configuration.        These would applied to caches programmatically created through the CacheManager.  The following attributes is required for defaultcache:maxinmemory-sets the maximum number of objects that 'll is created in memory eternal-sets whether elements is eternal.        If Eternal, timeouts is ignored and the element is never expired. Timetoidleseconds-sets the time to idle for an element before it expires. Was only used if the element was not eternal. Idle time is now-last accessed time timetoliveseconds-sets the time-to-live for a element before it expires. Was only used if the element was not eternal.             TTL is now-creation time overflowtodisk-sets whether elements can overflow to disk time the In-memory cache               has reached the maxinmemory limit. --<defaultcache maxelementsinmemory= "1" eternal= "false" timetoidleseconds= "+" Tim etoliveseconds= "overflowtodisk=" "true"/></ehcache>
Testsessioncache



TestQueryCache2


Testupdatetimestampcache


Using Ehcache to generate a cache file in d:/cache/



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. If you want to reprint, please specify the source: Http://blog.csdn.net/lindonglian

Hibernate (12) session cache and level two cache

Related Article

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.