Experience 15-hibernate Optimization 2-cache (first-level, two-level)

Source: Internet
Author: User
Tags bulk insert ord

1. Caching Overview

Caching (cache) is a set of instances of collections in memory in a Java application. It keeps a backup of the data in a permanent storage source (such as a file on a hard disk or a database), and it reads and writes faster than a hard drive. The application reads and writes directly to the data in the cache at run time, scheduling the data in the cache only at certain times to synchronize updates to the data store source. If the amount of data stored in the cache is very large, the hard disk is also used as the cached physical media.

Caching helps to improve the performance of applications by reducing the frequency with which applications can read and write to persistent data storage sources directly.

The implementation of the cache requires not only hardware (memory) as a physical medium, but also software for managing policies such as cached concurrency access and expiration.

2 Cache Range Classification

The scope of the cache determines the life cycle of the cache and who can access it. The scope of the cache is divided into the following three categories:

1 Transaction scope: The cache can only be accessed by the current transaction. The life cycle of the cache depends on the lifecycle of the transaction, and when the transaction ends, the cache ends the lifecycle. In this range, the cached media is memory. Note: The first-level cache, which is the session cache, is actually a transaction-scoped cache.

2 Process scope: caching is shared by all transactions within the process. These transactions may be concurrent access caching , so the necessary transaction isolation mechanism must be taken on the cache. Note: Level Two caching is a process-wide cache.

3 Cluster scope: in a clustered environment, caching is shared by a machine or by a process of multiple machines. Cached data is replicated to each process node in the cluster environment, which guarantees data consistency across the cache through remote communication. For most applications, cluster-wide caching should be used sparingly, because the speed of access is not necessarily faster than accessing database data directly.

3. Concurrent access policies for caching

Concurrency issues occur in a process-wide or cluster-wide cache . Therefore, you can set a concurrency access policy of type 4, each of which corresponds to a transaction isolation level. The higher the isolation level of a transaction, the lower the concurrency performance.

1 transaction type (transactional) policy

2) Read-write (read-write) strategy

3) Non-rigorous read-write (nonstrict-read-write) strategy

4) Read-only (read-only) policy

Cache in 4.Hibernate

The level two cache is provided in Hibernate, and the first level of caching is the session-level cache, which is a transaction-scoped cache.

The second level of caching is the sessionfactory level cache, which is a process-scoped cache that can be configured and changed, and can be dynamically loaded and unloaded.

Hibernate also provides a query cache for query results that relies on level two caching.

5. First-level cache management

the session-level cache is automatically managed by Hibernate . When the application invokes the session's Crud method and invokes the Query interface list (), iterate (), and so on, if the corresponding object does not exist in the session cache, hibernate will add the modified object to the session cache. If this object already exists in the session cache, it is not necessary to go to the database loading, but to use this object directly in the cache, which can reduce the frequency of accessing the database and improve the running efficiency of the program. When hibernate cleans up the cache (the default is to commit the transaction), hibernate synchronizes the data state in the database based on the state of the objects in the cache, emptying all the objects in the session cache when it closes.

First- level caching does not control the number of caches, so pay attention to the possibility of memory overflow when you bulk manipulate data ;

evict (Object obj): Clears the specified persisted object from the cache.

Clear (): clears all persisted objects in the cache.

flush (): An operation that cleans the cache (when the data in the cache is not lost), lets the cache and the database execute a series of SQL statements synchronously, but does not commit the transaction .

commit (): Call the Flush () method first, and then commit the transaction . means committing a transaction, which means that the database operation is permanently preserved.

Can write a for loop, the session can be inserted in batches of tens of thousands of data. As in the following code:

for (int i=0;i<10000;i++) {

Session.save (object);

}

The code that writes this will create a problem. Makes the cache of 10,000 objects all present in memory, which increases the pressure on the memory. So you should periodically clean up the session cache.

When you bulk INSERT or bulk update, you must control the size of the first cache by frequently calling the session's flush () and later calling clear () so that the memory can guarantee sufficient space.

6. Management of Level two cache

The second-level cache is a sessionfactory-level cache that is used as follows:

1 when executing a conditional query, issue a SQL statement such as "SELECT * FROM table_name where ..." to query the database and get all the data objects at once.

2 Put all the data objects obtained into the level two cache according to the ID.

3 when the hibernate according to the ID access to data objects, first from the session cache, check, if configured with level two cache, then check from level two cache, and then query the database, the results according to the ID into the two-level cache.

4 When the data is deleted, updated and added, it is also updated to the level two cache.

Hibernate's level Two caching strategy is a caching strategy for the ID query, which has no effect on the tuning query. To do this, hibernate improves query caching for conditional queries alone.

7 Common Cache Plug-ins

The hibernate level two cache is a plug-in. The following are several commonly used cache plug-ins.

8. Level Two cache configuration

When configuring level two caching, consider the question of deciding which persistence classes need to use level two caching, which one the cached concurrency access policy chooses, and then selecting the appropriate cache plug-in based on these conditions to edit the plug-in's configuration file.

9. Query caching

You can enable query caching if you are using the same criteria values for a conditional query in actual use.

The process of Hibernate query caching policy is as follows.

1 The first time a conditional query is executed, hibernate first consists of a query Key,query key that includes the request information for the conditional query based on these criteria values.

2 in the subsequent process with the same condition value to execute the query is, hibernate first according to the query cache to find the corresponding results list, if present, return. If it does not exist, check the database, and then the results list can be stored in the query cache, based on query.

Therefore, you can benefit from the query caching policy only if you frequently use the same parameter values for the same criteria query.

To use the query caching procedure:

1). Configure Query Caching

Hibernate provides 3 cache areas related to queries.

Default Query cache area: Org.hibernate.cache.StandardQueryCache

User-defined query cache area

Timestamp Cache area: Org.hibernate.cache.UpdateTimestampCache

Set the properties of the query cache area in the Ehcache configuration file ehcache.xml.

<ehcache>

<!--set properties for the default query cache area-->

<cache name= "Org.hibernate.cache.StandardQueryCache"

maxelementsinmemory= "50"

Eternal= "false"

Overflowtodisk= "true"

timetoidleseconds= "3600"

timetoliveseconds= "7200"

/>

<!--set the properties of the timestamp cache area-->

<cache name= "Org.hibernate.cache.UpdateTimestampsCache"

maxelementsinmemory= "500"

Eternal= "true"

Overflowtodisk= "true"

/>

<!--set properties for custom named query cache areas-->

<cache name= "Mycacheregion"

maxelementsinmemory= "1000"

Eternal= "false"

Overflowtodisk= "true"

timetoidleseconds= "3600"

timetoliveseconds= "7200"

/>

</ehcache>

2). Open Query Cache

Add the following configuration to the Hibernate global configuration file to start the query cache.

<!--enable query caching-->

<property name= "Cache.use_query_cache" >true</property>

3. Use query caching in application code

Although the query cache is set up in the above steps, Hibernate ignores the query cache by default when executing a conditional query. If you want to enable query caching, you should call the Setcacheeable (True) method of the query interface. (There are specific case studies below)

10. First-level cache case Analysis

Hibernate.cfg.xml To configure the following data:

<!--turn on level two cache-->

<property name= "Cache.use_second_level_cache" >true</property>

<!--provides level two cache Plug-ins (cache class)-->

<property name= "Cache.provider_class" >org.hibernate.cache.EhCacheProvider</property>

<!--open Query cache-->

<property name= "Cache.use_query_cache" >true</property>

Do not imitate the test, will be the database crash caused the panic, the number is too large will make the console constantly brush screen, resulting in myeclipse panic

@Test

publicvoid Testcache () {

Session session = Hibernateutil.getsession ();

Session.begintransaction ();

for (int i = 0; i < i++) {

Customer C = new customer ();

C.setcname ("Kay" + i);

Session.save (c);

for (int j = 0; J < + j) {

Orders o = new orders ();

O.setoname ("keyboard" + j);

Set<orders> ord = new hashset<orders> ();

Ord.add (o);

C.setord (ORD);

Session.save (o);

if (j% 50 = 0) {

Session.flush ();

Session.clear ();

}

}

}

Session.gettransaction (). commit ();

Hibernateutil.close ();

}

Test Cache Cache

@Test

publicvoid Testcache () {

Session session = Hibernateutil.getsession ();

Session.begintransaction ();

User user = (user) session.get (user). Class, 1); The first time the curd is executed, the session is created, the data is fetched from the database, so there is data, there are SQL statements

System.out.println (User.getname ());

System.out.println ("------------------");

Clears the user object, at which point the Get () method will re-establish a session cache, and there will be SQL statement output

Session.evict (user);

User User1 = (user) session.get (user). Class, 1); The second time the curd is executed, no session is created, no data is fetched from the database, so there is no SQL statement, and data is obtained from the session cache

System.out.println (User1.getname ());

Session.gettransaction (). commit ();

Hibernateutil.close ();

In the later experiment, if the session of the Util class is closed with a session that is not in the thread pool, it will not be implemented, and an error is closed.

System.out.println ("================");

Session = Hibernateutil.getsession ();

Session.begintransaction ();

user = (user) session.get (user). Class, 1); The first time the curd is executed, the session is created, the data is fetched from the database, so there is data, there are SQL statements

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.