Delayed loading and caching in Hibernate, and delayed loading in hibernate

Source: Internet
Author: User

Delayed loading and caching in Hibernate, and delayed loading in hibernate
What is delayed loading?

Delayed loading means that when an application wants to obtain an object from the database (when the value of the lazy attribute is not set to false), Hibernate only obtains the OId of the object that meets the condition from the database to generate a proxy object, the object is not loaded.

The corresponding value is loaded only when you access the properties of this object. In short, the query data volume is reduced as much as possible.

How to configure delayed Loading

In Hibernate, the lazy attribute in the. hbm configuration file is used to accompany the value. In addition, the lazy attribute has different locations and has different roles and values. Next, we will introduce in detail the different values and functions of different positions.

Lazy in Class labels:

The following lazy values are available in the Class label Class: true (default value: delayed loading) and false (immediate loading:

If the value of lazy is false, the application immediately loads all attribute values (excluding custom attributes) when obtaining objects from the database)

Take the employee table as an example. The test case is as follows:

Employee table structure:

Employee entity:

Hbm ing file of employee table:

Test code:

Test results:

From the results, we can see that the emp object does not perform delayed loading, but the attributes referenced by the stored Department (Dept) object are not loaded.

Let's take a look at the result when the value of the lazy attribute is true.

We can see that the lazy attributes, whether True or false, have the same results! Why? Should the value of the Lazy attribute be "true" delayed loading?

Note: we used the get method to get the employee object when writing the test case above. I also mentioned in my previous blog that the get method of the session object does not support delayed loading and will ignore the class-level lazy. attribute! We will replace the get method with the load method for testing.

From this we can see that when the lazy property value is true, Hibernate does not load all attribute values at once. Only when the program needs to load it, thus reducing the burden of interaction with the database, this improves program performance, which is also the goal of delayed loading!

Lazy in many-to-one Association

If you want to immediately load the associated custom type attribute while obtaining the object, you need to set the lazy attribute in its many-to-one configuration. The value of the lazy attribute here is: proxy: delayed loading (default), no-proxy: no agent delayed loading, false: load now

For example, we can add the lazy attribute value to false on the basis of instance 1 to test again:

Lazy attribute in the Set Element

We know that if the object contains a set of other entities, You need to configure the set element in the hbm file to map between tables. In the set element, you can also add the lazy attribute with the value: true: delayed loading (default value), false: immediate loading, extra: enhanced delayed loading.

Here, we will not test the value of false to test the difference between true and extra. We introduce the Dept (department) class on the basis of instance 1 for testing:

Department entity class:

Department table ing file:

Test code:

The property value of lazy is true:

The property value of Lazy is extra:

No Session problems caused by delayed Loading

When we write a layer-based B/s program, it is often because the Session is closed in advance and the data is not loaded completely, causing the no Session exception:

The cause of this exception is that the Code for local operation data is written in the DAO and Biz layers, but the two layers are not responsible for data presentation. When we display data on the jsp page, the Session has been closed and data related to delayed loading is not loaded into the object, when the jsp page accesses the object attributes, Hibernate tries to use the Session object to interact with the database and finds that there is no available Session object, which causes this exception.

The local approach to this problem is to store Session objects in the presentation layer using filters. The following code creates a filter:

Configure the filter in the web. xml file:

After the above operations, the no Session problem can be solved. Of course, there are other solutions, but these solutions are the most widely used and well-developed solutions,

Cache

Definition of Cache

Cache is a separate space for storing non-critical data with low modification frequency and frequent queries to reduce the interactions between applications and databases! It is a solution that exchanges a certain range of space for the speed and performance of the user's data query from the database!

Cache is generally divided into the following types:

Internal cache, secondary cache, query cache, and third-party cache.

Internal Cache

In Hibernate, the internal cache is also called the first-level cache and the transaction-level cache. It is automatically maintained by Hibernate and cannot be detached. The lifecycle of the Session object is the same as that of the Session object. When the Session is closed, the cache is automatically recycled. As follows:

The running result is as follows:

From the results, we can find that when the Hibernate value is queried twice, an SQL statement is generated, that is, only the first query and the database are interacted, and put the queried object into the internal cache. When the second query finds that the object already exists in the internal cache, Hibernate directly returns the object and does not interact with the database, in addition, the memory addresses of the objects in the two queries are identical. Therefore, we can conclude that the cache references the memory address of the object rather than the attribute values of the object!

Level 2 Cache

The second-level cache is a configurable plug-in that is a cache within a process or cluster and can be shared by all sessions.

Second-level cache Configuration

There are many plug-ins that configure level-2 cache in Hibernate. The following uses the EHCache plug-in as an example to configure level-2 cache.

1. Introduce the following jar package.

Ehcache-1.2.3.jar core library

Backport-util-concurrent.jar

Commons-logging.jar

2. Configure Hibernate. cfg. xml to enable Level 2 Cache

<Propertyname ="Hibernate. cache. use_second_level_cache"> True </property>

3. Configure the second-level cache vendor

<Property name ="Hibernate. cache. provider_class"> Org. hibernate. cache. EhCacheProvider </property>

Note: The property element must be above the mapping element.

4. Configure the class that can enter the second-level cache

<Class-cache usage ="Read-write"Class ="Cn. happy. entity.Emp"/>

5. Introduce the ehcache. xml file in the Classpath directory.

After the above five steps, you can put the Dept object into the second-level cache. Write the test case below.

Test results:

From the results, we can open the second query department without generating an SQL statement, but the objects printed twice are not the same memory address, this is because what is stored in the second-level cache is not a reference of the object's memory address but a bulk attribute of the object (it can be viewed as the attribute values of each object) therefore, when accessing the secondary storage swap, we need to re-assemble these attributes in the memory into a complete object. If you take a closer look, you will find that Hibernate will still generate SQL statements when we visit the employee collection for the second time. That is because the above level-2 Cache configuration is for the class level. If you want to cache the employee set, you need to add the set cache configuration in the hibernate. cfg. xml configuration file. The content is as follows:

Note: This configuration must be the next element of the mapping element.

Then we run the test and the result is as follows:

You may be surprised when you see the results. When I didn't configure the set cache, he only generated one SQL statement. How did I change it into two SQL statements after I completed my stay? However, you should note that the two SQL statements are exactly the same and are queried Based on the OID of the employee object! Where does the OID of the employee object come from? That's right. It is obtained from the second-level cache. As to why the OID of the employee object is cached and other attribute values are not cached, the reason is that the employee object does not have a second-level cache, so it cannot enter the second-level cache, so it cannot get its other attribute values from the second-level cache. We will configure the second-level cache for the employee object before testing.

The result is as follows:

Query Cache Query cache configurations

Add the preceding elements to the hibernate. cfg. xml configuration file to enable Level 2 cache. You must call query1.setCacheable (True);

The following is a test case:

Test results:

Note:

1. the query cache is based on the second-level cache. You must configure the second-level cache When configuring the query cache. Otherwise, the following exception will be thrown.

2. the query cache stores the reference of the object memory address rather than the object's bulk attribute.

3. the query cache is based on the two HQL query statements converted internally by Hibernate. The generated SQL statements remain the same and decide whether to interact with the database instead of the following test cases based on the OID of the object. it is an object with the same OID but will still interact with the database!

Test results:

Latency loading and cache Legacy problems The Lazy attribute and fetch attribute are used together.

The one-to-many or many-to-many retrieval policies are jointly determined by lazy and fetch. Lazy: determines the initialization time of the associated object, and Fetch: determines the SQL statement construction form. The values of the Fetch attribute are Join: urgent left Outer Join, Select: Multiple simple SQL statements (default value), and Subselect: subquery. When the Fetch attribute value is join, the lazy attribute is ignored and the immediate loading policy is used. For example, a department numbered 5, even if the set attribute in the set element mapped to the employee set in the department ing file is set to true or extra, the set of all employees in the Department is immediately loaded, the SQL statement generated by Hibernate is as follows:

Difference between the list method and iterate method of the Query interface

1. Different types are returned. list and iterate return Iterator,
2. the method for getting data is different. The list will directly query the database, and the iterate will first retrieve the IDs in the database, and then find the IDs in the cache when traversing an object. If it cannot be found, the id is used as the condition to send an SQL statement to the database. If no data exists in the cache, the number of queries to the database is n + 1.
3. iterate queries the Level 2 Cache. The list will only be cached, but will not be cached (unless combined with the query cache ).
4. Each object in the list returned by List is the original object, and the object returned by iterate is the proxy object.

Cache internal storage implementation

1. Object Data in the cache is in the form of a map set

2. Both the level-1 cache and level-2 Cache use the OID of the object as the key value combined with map, and the query cache uses the SQL statement generated inside Hibernate as the key value.

3. The value of the map set in the first-level cache and query cache stores the reference of the memory object, while the second-level cache stores the object's bulk attribute.

4. when the application needs to obtain data from the database, Hibernate will retrieve the level-1 cache or query cache> level-2 cache or query whether any qualified data exists in the cache. If yes, it will directly return the data that is not in progress with the database. interaction, otherwise, an SQL statement is generated to interact with the database to obtain the corresponding data and then return it. Then, the data is placed in the first-level cache> second-level cache or query cache.

Save Level 2 cache to Hard Disk

Set the path attribute value of the diskStore element in the ehcache. xml configuration file under the classpath directory to the path to be saved and set the maxElementsInMemory attribute value in the cache element to 0.

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.