Cache in hibernate

Source: Internet
Author: User


Hibernate provides two levels of Cache

Session-level cache:

It is a cache within the scope of transactions. This level of cache is managed by hibernate, and no intervention is required in general.

Sessionfactory-level cache:

It is a process-specific cache.

Enable secondary cache conditions:

1. Rarely modified

2. Many system modules are required

3. Data is not private and shared.

How to configure the second-level cache[Each method before the operation to commons-logging-1.1.1.jar ]:

1. Configure in the ing file of the class

2. Configure in the configuration file

3. In the ehcache. xml file, configure [this file can specify the location where the cache is stored to the hard disk]

Attributes in the ehcache. xml file:

1. <diskstore>: Specifies a directory. When ehcache writes data to the hard disk, it writes the data to this directory. The default value is c: \ windows \ temp.

2. <defaultcache>: sets the cache's default data past policy.

3. <cache>: Set a data expiration Policy for a specific named cache.

4. Each named cache represents a cache region, and each cache region has its own data expiration policy. The named cache mechanism allows you to set data expiration policies at the granularity of each class and each set of classes.

Attributes of the cache element:

1. Name: Set the cache name. The value is the name of the fully qualified name of the class or the set of classes.

2. maxelementsinmeory: sets the maximum number of objects that can be stored in the memory-based cache.

3. Eternal: sets whether the object is permanent. True indicates that the object will never expire.

4. timetoidleseconds and timetoliveseconds attributes: The default value is false.

5. timetoidleseconds: sets the maximum idle time of the object, in seconds. The object expires after this time. When an object expires, ehcache clears it from the cache. If the value is 0, the object can be idle for an indefinite period of time.

6. timetoliveseconds: sets the maximum time for an object to survive. If the maximum time is exceeded, the object expires. If the value is 0, the object can be stored in the cache indefinitely. The value of this attribute must be greater than or equal to the value of timetoidleseconds.

7. overflowtodisk: sets whether to write the overflow object to the hard disk-based Cache after the number of objects in the internal cache reaches the threshold.

8. diskpersistent: Specifies whether the persistence object is set to true when the JVM ends. The default value is false.

9. diskexpiryintervalseconds: Specifies the polling time of the listener thread dedicated to clearing expired objects.

 

Example:

1. Fetch data from the second-level cache

// Test the second-level cache

/*

* After the session is closedHibernateAnd then query the same data,

* Will certainly be issuedSQLHowever, if the current object is cached in the second-level cache, the session is closed,

* The second-level cache does not disappear, and the same data will be queried at this time and will not be sentSQLStatement

**/

@ Test

Public voidTestcache (){

Session session = hibernateutil.Getsession();

Transaction Tx = session. begintransaction ();

Customers customer = (customers) Session. Load (customers.Class, 2 );

System.Out. Println (customer. getemail ());

TX. Commit ();

Session. Close ();

Session = hibernateutil.Getsession();

Tx = session. begintransaction ();

Customer = (customers) Session. Load (customers.Class, 2 );

System.Out. Println (customer. getpetname ());

TX. Commit ();

Session. Close ();

}

Running result:

Hibernate: selectcustomers0 _. ID as id0_0 _, customers0 _. realname as realname0_0 _, customers0 _. pass as pass0_0 _, customers0 _. sex as sex0_0 _, customers0 _. petnameas petname0_0 _, customers0 _. email as email0_0 _, customers0 _. rdate as rdate0_0_from pros. MERs
Customers0 _ Where customers0 _. ID =?

Aa@aa.com

Bbb

Note: When the second-level cache is disabled, two SQL statements are displayed in the running result.

 

2. synchronize data to the second-level cache

// Test the operations on the object, which will be synchronized to the second-level cache

@ Test

Public voidTestupdate (){

Session session = hibernateutil.Getsession();

Transaction Tx = session. begintransaction ();

Customers customer = (customers) Session. Load (customers.Class, 2 );

System.Out. Println (customer. getemail ());

Customer. setemail ("aaa123@qq.com ");

TX. Commit ();

Session. Close ();

Session = hibernateutil.Getsession();

Tx = session. begintransaction ();

Customer = (customers) Session. Load (customers.Class, 2 );

System.Out. Println (customer. getemail ());

TX. Commit ();

Session. Close ();

}

Running result:

Hibernate: selectcustomers0 _. ID as id0_0 _, customers0 _. realname as realname0_0 _, customers0 _. pass as pass0_0 _, customers0 _. sex as sex0_0 _, customers0 _. petnameas petname0_0 _, customers0 _. email as email0_0 _, customers0 _. rdate as rdate0_0_from pros. MERs
Customers0 _ Where customers0 _. ID =?

Aa@aa.com

Hibernate: updatepros. Customers set realname = ?, Pass = ?, Sex = ?, Petname = ?, Email = ?, Rdate =? Whereid =?

Aaa123@qq.com

 

4. Synchronize the changes to the second-level cache:

// When the value is changed, the second-level cache reloads the data to ensure data consistency.

@ Test

Public voidTestupdatetimestampcache (){

Session session = hibernateutil.Getsession();

Transaction Tx = session. begintransaction ();

Customers customer = (customers) Session. Load (customers.Class, 1 );

System.Out. Println (customer. getpetname ());

Query query = session. createquery ("Update customers C set C. petname = 'wang' where c. ID = 1 ");

Query.exe cuteupdate ();

TX. Commit ();

Session. Close ();

Session = hibernateutil.Getsession();

Tx = session. begintransaction ();

// Re-query the database because the data in the cache is inconsistent with the data in the database.

Customer = (customers) Session. Load (customers.Class, 1 );

System.Out. Println (customer. getpetname ());

TX. Commit ();

Session. Close ();

}

Running result:

Hibernate: selectcustomers0 _. ID as id0_0 _, customers0 _. realname as realname0_0 _, customers0 _. pass as pass0_0 _, customers0 _. sex as sex0_0 _, customers0 _. petnameas petname0_0 _, customers0 _. email as email0_0 _, customers0 _. rdate as rdate0_0_from pros. MERs
Customers0 _ Where customers0 _. ID =?

34

Hibernate: updatepros. Customers set petname = 'wang' where id = 1

Hibernate: selectcustomers0 _. ID as id0_0 _, customers0 _. realname as realname0_0 _, customers0 _. passas pass0_0 _, customers0 _. sex as sex0_0 _, customers0 _. petname as petname0_0 _, customers0 _. email as email0_0 _, customers0 _. rdate as rdate0_0 _ frompros. MERs
Customers0 _ Where customers0 _. ID =?

Wang

When the query statement is update MERs C set C. petname = Wang where c. ID = 1, an exception is thrown. Be sure to check the type of the element to be modified.

5. cache to a temporary directory

// Test whether cache overflow is stored in the temporary directory

@ Test

Public voidTestowerflow (){

Session session = hibernateutil.Getsession();

Transaction Tx = session. begintransaction ();

Query query = session. createquery ("from MERs C ");

Query. List (). Size ();

TX. Commit ();

Session. Close ();

}

Running result:

Hibernate: selectcustomers0 _. ID as id0 _, customers0 _. realname as realname0 _, customers0 _. pass aspass0 _, customers0 _. sex as sex0 _, customers0 _. petname as petname0 _, customers0 _. email as email0 _, customers0 _. rdate as rdate0 _ from pros. customerscustomers0 _

6. session. iterate method

// Iterator first retrieves the qualified IDs in the database, and then searches for the objects in the level-1 and level-2 caches Based on the IDs.

// (Only one database can be queried at a time, which may lead to n + 1 queries)

/*

* Because the session is closed for the first time, all the data in the first-level cache does not exist, and the data in the second-level cache does not disappear.

* All data smaller than 2 should be stored in the second-level cache, and data larger than 2 should be queried in the database.

**/

@ Test

Public voidTestiterator (){

Session session = hibernateutil.Getsession();

Transaction Tx = session. begintransaction ();

Query query = session. createquery ("from customers C where c. ID <2 ");

Query. List (). Size ();

TX. Commit ();

Session. Close ();

Session = hibernateutil.Getsession();

Tx = session. begintransaction ();

Query = session. createquery ("from MERs C ");

Iterator <customers> it =Query. iterate ();

While(It. hasnext ()){

System.Out. Println (it. Next (). getemail ());

}

TX. Commit ();

Session. Close ();

}

Running result:

Hibernate: selectcustomers0 _. ID as id0 _, customers0 _. realname as realname0 _, customers0 _. pass aspass0 _, customers0 _. sex as sex0 _, customers0 _. petname as petname0 _, customers0 _. email as email0 _, customers0 _. rdate as rdate0 _ from pros. customerscustomers0 _
Where customers0 _. ID <2

Hibernate: selectcustomers0 _. ID as col_0_0 _ from pros. Customers customers0 _

EWR

Hibernate: selectcustomers0 _. ID as id0_0 _, customers0 _. realname as realname0_0 _, customers0 _. pass as pass0_0 _, customers0 _. sex as sex0_0 _, customers0 _. petnameas petname0_0 _, customers0 _. email as email0_0 _, customers0 _. rdate as rdate0_0_from pros. MERs
Customers0 _ Where customers0 _. ID =?

Aaa123@qq.com

Hibernate: selectcustomers0 _. ID as id0_0 _, customers0 _. realname as realname0_0 _, customers0 _. pass as pass0_0 _, customers0 _. sex as sex0_0 _, customers0 _. petnameas petname0_0 _, customers0 _. email as email0_0 _, customers0 _. rdate as rdate0_0_from pros. MERs
Customers0 _ Where customers0 _. ID =?

Aa@aa.com

Hibernate: selectcustomers0 _. ID as id0_0 _, customers0 _. realname as realname0_0 _, customers0 _. pass as pass0_0 _, customers0 _. sex as sex0_0 _, customers0 _. petnameas petname0_0 _, customers0 _. email as email0_0 _, customers0 _. rdate as rdate0_0_from pros. MERs
Customers0 _ Where customers0 _. ID =?

32432@ww.con

Hibernate: selectcustomers0 _. ID as id0_0 _, customers0 _. realname as realname0_0 _, customers0 _. pass as pass0_0 _, customers0 _. sex as sex0_0 _, customers0 _. petnameas petname0_0 _, customers0 _. email as email0_0 _, customers0 _. rdate as rdate0_0_from pros. MERs
Customers0 _ Where customers0 _. ID =?

Rty

7. query Cache

/*

* Test query Cache

* The query cache depends on the second-level cache. All the second-level caches must be enabled for query cache to take effect.

**/

@ Test

Public voidTestquerycache (){

Session session = hibernateutil.Getsession();

Transaction Tx = session. begintransaction ();

Query query = session. createquery ("select C from MERs c Where C. ID = 2 ");

/*

* Set query Cache

* If the query cache exists, return directly

* If the query does not exist, query the database and place the query results in the cache.

**/

Query. setcacheable (True);

Query. List ();

TX. Commit ();

Session. Close ();

Session = hibernateutil.Getsession();

Tx = session. begintransaction ();

Query = session. createquery ("select C from MERs c Where C. ID = 2 ");

Query. setcacheable (True);

Query. List ();

TX. Commit ();

Session. Close ();

}

Running result:

Hibernate: selectcustomers0 _. ID as id0 _, customers0 _. realname as realname0 _, customers0 _. pass aspass0 _, customers0 _. sex as sex0 _, customers0 _. petname as petname0 _, customers0 _. emailas email0 _, customers0 _. rdate as rdate0 _ from pros. MERs
Customers0 _ wherecustomers0 _. ID = 2

Hibernate: selectcustomers0 _. ID as id0 _, customers0 _. realname as realname0 _, customers0 _. pass aspass0 _, customers0 _. sex as sex0 _, customers0 _. petname as petname0 _, customers0 _. email as email0 _, customers0 _. rdate as rdate0 _ from pros. customerscustomers0 _
Where customers0 _. ID = 2

 

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.