Hibernate-latency loading mechanism for performance optimization

Source: Internet
Author: User

Delayed Loading
 
The delayed loading mechanism is proposed to avoid unnecessary performance overhead. The so-called delayed loading means that data loading is performed only when data is actually needed. Hibernate provides delayed loading of object objects and delayed loading of collections, and delayed loading of attributes in Hibernate3. Next we will introduce the details of these types of delayed loading.
 
 
By default, Hibernate uses the following types of delayed loading.
 
1) when the load () method on the Session is called to load an object, delayed loading is used.
 
2) When a Session records an object, it uses delayed loading for the set attribute values in the object.
 
3) When a Session loads an object, it uses delayed loading for another object with multiple single-ended Associations (one-to-one, one-to-one ).
 
 
 
Next we will introduce the details of these types of delayed loading.
 
A. Delayed loading of object:
 
To use delayed loading for object objects, you must configure the object ing configuration file as follows:
 
 
Java code collection code
 
<Span style = "font-size: large;">

<Class name = "com. neusoft. entity. User" table = "user" lazy = "true">

......

</Class>

</Hibernate-mapping>
</Span>
 
You can enable the delayed loading feature of an object by setting the lazy attribute of the class to true. If we run the following code:
 
 
 
Java code collection code
 
<Span style = "font-size: large;"> User user = (User) session. load (User. class, "1"); (1)
System. out. println (user. getName (); (2) </span>
 
When running at (1), Hibernate does not initiate data query. If we use some debugging tools (such as JBuilder2005's Debug tool ), observe the memory snapshot of the user object. We are surprised to find that the returned User $ EnhancerByCGLIB $ bede8986 type object and its attribute is null. What is the problem? I still remember that the session. load () method previously mentioned will return the proxy class Object of the object. Here, the returned object type is the proxy class Object of the User object. In Hibernate, CGLIB is used to dynamically construct the proxy class object of a target object, and the proxy class object contains all the attributes and methods of the target object, all attributes are assigned null values. Whether the values get attribute is null. If it is not null, The getName method of the target object is called. If it is null, a database query is initiated to generate an SQL statement similar to this: select * from user where id+'1' then to query data, construct the target object, and assign the value to the cglib?calback_0.tar get attribute.
 
In this way, through an intermediate proxy object, Hibernate achieves object loading delay. Only when a user initiates an action to obtain object attributes can the user initiate a database query operation. Therefore, the delayed loading of objects is completed through the intermediate proxy class, so only session is available. the load () method uses the object to delay loading, because only the session. the load () method returns the proxy class Object of the object class.
 
 
B. Delayed loading of Collection types:
 
 
In the delayed Loading Mechanism of Hibernate, it is of the most significant significance for the application of the set type, because it may greatly improve the performance, so Hibernate has made a lot of efforts, this includes the independent implementation of JDK Collection. In one-to-Multiple Association, the Set defined to hold the associated object is not java. util. set type or its subtype, but net. sf. hibernate. collection. set type. Hibernate implements delayed loading of Set types by using custom collection classes. To use delayed loading for the collection type, we must configure the related section of our object class as follows:
 

Java code collection code
 
<Span style = "font-size: large;">

<Class name = "com. neusoft. entity. User" table = "user">

.....

<Set name = "addresses" table = "address" lazy = "true" inverse = "true">

<Key column = "user_id"/>

<One-to-define class = "com. neusoft. entity. Arrderss"/>

</Set>

</Class>

</Hibernate-mapping>
</Span>
 
Set the lazy attribute of the <set> element to true to enable the delayed loading feature of the set type. Let's look at the following code:
 

 

Java code collection code
 
<Span style = "font-size: large;"> User user = (User) session. load (User. class, "1 ");

Collection addset = user. getAddresses (); (1)

Iterator it = addset. iterator (); (2)

While (it. hasNext ()){

Address address = (Address) it. next ();

System. out. println (address. getAddress ());

}
</Span>
 
When the program is executed at (1), no query is initiated for the associated data to load the associated data. Only when the program runs at (2, the real data read operation starts. At this time, Hibernate searches for object objects that meet the condition based on the Qualified Data Index in the cache.
 

 
 
Here we introduce a new concept-Data Index. Next we will first take a look at what is data index. In Hibernate, the set type is cached in two parts. First, the IDs of all objects in the set are cached, and then the object IDs are cached, it is the so-called data index. When you look for a data index, if the corresponding data index is not found, a select SQL statement is executed to obtain Qualified Data and construct a collection of Entity objects and data indexes, then return the collection of object objects and include the object objects and data indexes in the cache of Hibernate. On the other hand, if the corresponding data index is found, the id list is retrieved from the data index, and the corresponding entity is searched in the cache based on the id. If it is found, it is returned from the cache, if not, select SQL query is initiated. Here we can see another problem, which may affect the performance. This is a cache policy of the collection type. If we configure the collection type as follows:
 

Java code collection code
 
<Span style = "font-size: large;">

<Class name = "com. neusoft. entity. User" table = "user">

.....

<Set name = "addresses" table = "address" lazy = "true" inverse = "true">

<Cache usage = "read-only"/>

<Key column = "user_id"/>

<One-to-define class = "com. neusoft. entity. Arrderss"/>

</Set>

</Class>

</Hibernate-mapping>
</Span>
 

 

 
Here we apply the <cache usage = "read-only"/> Configuration. if this policy is used to configure the collection type, Hibernate will only cache the data index, instead of caching entity objects in the set. Run the following code for the above Configuration:
Java code collection code
 
<Span style = "font-size: large;"> User user = (User) session. load (User. class, "1 ");

Collection addset = user. getAddresses ();

Iterator it = addset. iterator ();

While (it. hasNext ()){

Address address = (Address) it. next ();

System. out. println (address. getAddress ());

}

System. out. println ("Second query ......");

User user2 = (User) session. load (User. class, "1 ");

Collection it2 = user2.getAddresses ();

While (it2.hasNext ()){

Address address2 = (Address) it2.next ();

System. out. println (address2.getAddress ());

}
</Span>
 
Run this code to get output similar to the following:
Select * from user where id = '1 ';
 
Select * from address where user_id = '1 ';
 
Tianjin
 
Dalian
 
Second query ......
 
Select * from address where id = '1 ';
 
Select * from address where id = '2 ';
 
Tianjin
 
Dalian
 
We can see that when the second query was executed, two queries were performed on the address table. Why? This is because after loading an object for the first time, according to the configuration of the cache policy of the collection type, only the collection data index is cached, and the object objects in the collection are not cached, therefore, when the object is loaded again for the second time, Hibernate finds the data index of the corresponding object, but it cannot find the corresponding object in the cache according to the data index, therefore, Hibernate initiates two select SQL queries based on the data index. This results in a waste of performance. How can we avoid this situation? We must specify a cache policy for the objects in the collection type. Therefore, we need to configure the collection type as follows:
Java code collection code
 
<Span style = "font-size: large;">

<Class name = "com. neusoft. entity. User" table = "user">

.....

<Set name = "addresses" table = "address" lazy = "true" inverse = "true">

<Cache usage = "read-write"/>

<Key column = "user_id"/>

<One-to-define class = "com. neusoft. entity. Arrderss"/>

</Set>

</Class>

</Hibernate-mappin </span>
 
At this time, Hibernate will cache the objects in the set type. If you run the above Code again based on this configuration, the following output will be obtained:
 
Select * from user where id = '1 ';
 
Select * from address where user_id = '1 ';
 
Tianjin
 
Dalian
 
Second query ......
 
Tianjin
 
Dalian
 
In this case, no SQL statement is used to query data indexes, because the Entity objects stored in the set type can be directly obtained from the cache.
 
 
C. Delayed attribute loading:
 
 
In Hibernate3, a new feature-delayed loading of attributes is introduced, which provides a powerful tool for obtaining high-performance queries. As mentioned above, when reading a big data object, there is a resume field in the User object, which is a java. SQL. the Clob type contains the user's resume information. When we load this object, we have to load this field every time, whether or not we really need it, in addition, reading such big data objects will bring about great performance overhead. In Hibernate2, we only break down the User class through the granularity subdivision of the surface performance we mentioned earlier (refer to the discussion in that section ), however, in Hibernate3, we can use the property delay loading mechanism to obtain the ability to read data from this field only when we really need to operate on this field, therefore, we must configure our object class as follows:
 
Java code collection code
 
<Span style = "font-size: large;">

<Class name = "com. neusoft. entity. User" table = "user">

......

<Property name = "resume" type = "java. SQL. Clob" column = "resume" lazy = "true"/>

</Class>

</Hibernate-mapping> </span> <span style = "white-space: normal;"> <span style = "font-size: large;">
</Span>
 
You can set true for the lazy attribute of the <property> element to enable delayed loading of the attribute. In Hibernate3, to achieve delayed loading of the attribute, the Class enhancement tool is used to enhance the Class file of the object Class. Through the Enhancement Tool, the logic of the callback mechanism of CGLIB is added to the object Class. Here we can see the delayed loading of the attribute, it is implemented through CGLIB. CGLIB is an open-source project of Apache. This class library can manipulate the bytecode of java classes and dynamically construct class objects that meet the requirements according to the bytecode. Based on the preceding configuration, run the following code:
 
Java code collection code
 
<Span style = "font-size: large;"> String SQL = "from User user where user. name = 'zx '";

Query query = session. createQuery (SQL); (1)

List list = query. list ();

For (int I = 0; I <list. size (); I ++ ){

User user = (User) list. get (I );

System. out. println (user. getName ());

System. out. println (user. getResume (); (2)

}
</Span>
 
When executed at (1), an SQL statement similar to the following will be generated:
 
Select id, age, name from user where name = 'zx ';
 
At this time, Hibernate will retrieve all the field data corresponding to the non-delayed loading attribute in the User object. When it is executed at (2), it will generate an SQL statement similar to the following:
 
Select resume from user where id = '1 ';
 
In this case, a real read operation is initiated on the resume field data.
 
 
 
Disable delayed Loading
 
Delayed loading will indeed bring benefits to the query of programs, but sometimes it is clear that the data needs to be loaded immediately. If Hibernate uses delayed loading by default, then it must be loaded to the database, this will reduce the efficiency. Therefore, you can flexibly control whether to use delayed loading based on the actual situation of the application. In Hibenate, you only need to modify the corresponding configuration to enable or disable the loading function.
 
1) when loading a single object, if you do not need to delay loading, you can use the get () method of the Session.
 
2) When a Session loads an object, it does not need to delay loading the set attribute values in the object, but needs to be loaded immediately. In this case, you can add the property lazy = false in the configuration elements (<set>, <bag>, <list>...) of the ing file.
 
3) When a Session loads an object, do not delay loading another object with multiple single-ended Associations (associated with a single-ended object, you can add the property lazy = false to the configuration elements (<one-to-one> and <allow-to-one>) of the single-ended Association in the ing file.
 

Author: ERDP Technical Architecture"

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.