Hibernate lazy-loading description

sponsored links
This article describes the Hibernate lazy loading can be divided into three parts: 1, physical object delay load; 2, a collection of types of delay in loading; property lazy loading.

Hibernate lazy loading:

Lazy loading mechanism is in order to avoid unnecessary performance overhead and put forward the so-called lazy loading is that when the data really need when we come to the genuine implementation of data loading operations. Provided in the Hibernate entity objects as well as a collection of delay in loading delays in loading, while in Hibernate3 also provides the right attributes lazy. Here we were introduced Hibernate lazy loading of these kinds of details.

A, Hibernate lazy loading of entities object delay load:

If you want to use lazy loading of the entity object must be in the physical mapping of the configuration file for the appropriate configuration, as follows:

  1. <Hibernate-mapping> <Class name = "com.neusoft.entity.User"
  2. table = "user" lazy = "true">
  3. ... ... </ Class> </ Hibernate-mapping>

By class of lazy property is set to true, to open the physical characteristics of the delayed loading. If we run the following code:

  1. User user = (User) session. Load (User.class, "1"); (1)
  2. System. Out. Println (user.getName ());( 2)

When running to (1), Office hours, Hibernate does not initiate a data query, if we are at this time through a number of debugging tools (such as JBuilder2005 the Debug tool) to observe the user at this time the object of memory snapshots, we will be surprised to find that At this point may be returned User $ EnhancerByCGLIB $ $ bede8986 types of objects and their attributes as null, which is how it? Remember earlier I had talked session.load () method will return a proxy class object physical object, where the returned object type is the User object's proxy class object. In the Hibernate by using CGLIB, to construct a target object dynamic proxy class object, and in the proxy class object contains all of the target object properties and methods, and all attributes are assigned to null. Through the debugger shows the memory snapshot, we can see the real time User objects, is included in the proxy object CGLIB $ CALBACK_0.target property, when the code runs to (2), Office hours, this time called user.getName () method, when given by CGLIB callback mechanism, in fact call the CGLIB $ CALBACK_0.getName () method, when you call the method, Hibernate will first check the CGLIB $ CALBACK_0.target property is null, if not empty , then call the target object's getName method, if empty, it will initiate database queries, the generated SQL statement like this: select * from user where'1 '; to query data, and construct the target object, and assign it to a CGLIB $ CALBACK_0.target properties.

In this way, through an intermediate proxy object, Hibernate implements lazy loading entities, and only when a user actually initiated the action to obtain physical object properties only when the real action will be initiated database queries. Therefore, the delayed entity loading is done through the intermediate proxy class, so only session.load () method will only delay the use of physical load, because only session.load () method will return a proxy class object entity class.

B, Hibernate lazy loading the set of types of delay:

In Hibernate's lazy loading mechanism for the collection types of applications, meaning the most significant, because it has the potential to significantly improve the performance, for Hibernate carried out a lot of efforts, including an independent realization of JDK Collection , we have one to many association, the definition is used to hold a collection of related object of the Set is not java.util.Set type or its sub-types, but net.sf.Hibernate.collection.Set type, by using a custom collection class implementation, Hibernate implements lazy loading collection types. In order to set the type to use lazy loading, we have the following configuration of our entity class on the associated parts:

  1. <Hibernate-mapping>
  2. <class name ="com.neusoft.entity.User" table ="user"> ... ..
  3. <Set name = "addresses" table = "address" lazy = "true"
  4. inverse = "true"> <key column = "user_id" />
  5. <one- to -many"com.neusoft.entity.Arrderss"/> </ set>
  6. </ class> </ Hibernate-mapping>

By <set> element lazy attribute set to true to open the collection type of lazy loading features. We see the following code:

  1. User user = (User) session. Load (User.class, "1");
  2. Collection addset = user.getAddresses (); (1)
  3. Iterator it = addset.iterator (); (2)
  4. while (it.hasNext ()) (Address address = (Address) it. next ();
  5. System. Out. Println (address.getAddress ());}

When the program execution to (1) Offices, the time will not initiate a query to load the associated data associated with the data, only to run to (2) Offices, the real data read operation will not start, then Hibernate will be According to the data cache eligible index to find qualified entity objects.

Here we introduce a new concept - data index, let's first take look at what is data indexing. Hibernate collection type in the right cache when the cache is divided into two parts, first of all entities in the cache set id list, and then cached entity object, the object id list of these entities is the so-called data index. When the search for data indexing, if not find the corresponding data index, then the implementation will be a select SQL, access to meet the requirements of the data, and construct a collection of physical objects and the data index, and then return a collection of physical objects and entity objects and data into an index into the cache of Hibernate. On the other hand, if the data to find the corresponding index data indexing remove id from list, and then under the id in the cache to find the corresponding entities, if found from the cache to return if not found, in initiating select SQL query. Here we see another issue that may have an impact on performance, which is a collection of types of caching policy. If we set the following configuration types:

  1. <Hibernate-mapping>
  2. <class name ="com.neusoft.entity.User" table ="user"> ... ..
  3. <Set name = "addresses" table = "address" lazy = "true"
  4. inverse = "true"> <cache usage=" read-only "/> <key column = "user_id" />
  5. <one- to -many"com.neusoft.entity.Arrderss"/> </ set>
  6. </ class> </ Hibernate-mapping>

Here we applied the <cache usage="read-only"/> configuration, if we adopt this strategy to configure the collection type, Hibernate will only index the data cache, rather than a collection of entity objects will be cached. As configured we run the following code:

  1. User user = (User) session. Load (User.class, "1");
  2. Collection addset = user.getAddresses ();
  3. Iterator it = addset.iterator ();
  4. while (it.hasNext ()) (Address address = (Address) it. next (); System. out. println (address.getAddress ());}
  5. System. Out. Println ( "Second query ... ...");
  6. User user2 = (User) session. Load (User.class, "1");
  7. Collection it2 = user2.getAddresses (); while (it2.hasNext ())
  8. (Address address2 = (Address) it2. Next ();
  9. System. Out. Println (address2.getAddress ());}

Run this code, will be similar to the following output:

  1. Select * from user where '1 ';
  2. Select * from address where user_id = '1 ';
  3. TianjinDalianSecond query ... ... Select * from address where '1 ';
  4. Select * from address where '2 ';
  5. TianjinDalian

We can see that the second query is executed, the implementation of the two pairs of address table query operation, why is this so? This is because when you first load an entity, based on the configuration of the collection type of caching strategy, data collection only index the cache, but did not set the entity object cache, so in the second re-load the entity , Hibernate entity to find the corresponding data index, but according to data indexing, but can not be found in the cache corresponding to the entities, so Hibernate according to the data found in the index was launched two select SQL query operation, where the performance resulted in waste, How can we avoid this situation? We must set the type of the entities designated caching strategy, so we have to configure the following types of collections:

  1. <Hibernate-mapping>
  2. <class name ="com.neusoft.entity.User" table ="user"> ... ..
  3. <Set name = "addresses" table = "address" lazy = "true"
  4. inverse = "true"> <cache usage=" read -write"/>
  5. <Key column = "user_id" />
  6. <one- to -many"com.neusoft.entity.Arrderss"/> </ set>
  7. </ class> </ Hibernate-mapping>

Hibernate collection type at this time would have also carried out in the entity cache, if the basis of this configuration re-run the above code, will be similar to the following output:

  1. Select * from user where '1 ';
  2. Select * from address where user_id = '1 ';
  3. TianjinDalianSecond query ... ... TianjinDalian

At this time there will not be indexed according to the data of the SQL query statement, because at this time can be obtained directly from the cache stored in a collection of entity object types.

C, Hibernate lazy-loading lazy load the properties:

In Hibernate3, the introduction of a new feature - the property lazy loading, this mechanism also provides for access to high-performance query a powerful tool. When we say in front of large data objects to read when the User object in the field, there is a resume of the field is a java.sql.Clob type that contains the user's curriculum vitae information, when we load the object, we must not do not have to load each time this field, regardless of whether we really need it, and this large data object to read in itself will bring significant performance overhead. In the Hibernate2, we are ahead of us talked about only through the performance of particle size breakdown of the surface to decompose User class, to solve this problem (please refer to the section of the exposition), but in Hibernate3, we can attribute to defer the increase contains a mechanism to give us only when we really need to operate in this field before going to the ability to read the field data, for which we have the following configuration of our entity class:

  1. <Hibernate-mapping>
  2. <class name ="com.neusoft.entity.User" table ="user"> ... ...
  3. <property name = "resume" type = "java.sql.Clob"
  4. column = "resume" lazy = "true" />
  5. </ class> </ Hibernate-mapping>

<property> Element through the lazy attribute set to open the properties of true delayed loading, in order to achieve the properties in the Hibernate3 delay loading a class using the booster to the Class of the entity class file enhanced processing, by enhancing device enhancements, will CGLIB callback mechanism for the logic, add entity class, where we can see that the property lazy loading, or through CGLIB to achieve. CGLIB is an open source Apache project, the library can manipulate java byte code classes, according to byte code to dynamically constructed to meet the requirements of the class object. Based on the above configuration we have run the following code:

  1. String sql = "from User user where user. Name = 'zx'";
  2. Query query = session.createQuery (sql); (1)
  3. List list = query.list ();
  4. for (int i = 0; i <list. size (); i + +)
  5. (User user = (User) list.get (i);
  6. System. Out. Println (user.getName ());
  7. System. Out. Println (user.getResume ()); (2)
  8. )

When the Executive to (1) Department, it will generate SQL similar to the following statement:

  1. Select id, age, name from user where name = 'zx';

Hibernate will then retrieve the User entity, all non-lazy properties of the corresponding field data, when the Executive to (2) Department, it will generate SQL similar to the following statement:

  1. Select resume from user where '1 ';

This time to launch a real field data on the resume read operation.
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Hibernate lazy-loading description

  • Hibernate connection pool configuration

    Hibernate connection pool configuration <! - Jdbc -> <property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver </ property> <property name="connection.url"> jdbc: oracle: thin: @ 10.203.14.132:15

  • hibernate to use the principle of

    The use of hibernate, implementation of data persistence. Has the following several processes. One configuration database connection information. Hibernate.config 2 configuration mapping. 3 use: the use of the process are the following steps: 3.1: Ge ...

  • hibernate generic generic DAO

    package org.lzpeng.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.springside.modules.orm.hibernate.Page; /** * * @version 2009-1-10 *

  • Struts2 + hibernate + spring problem user log in

    dao layer services layer action jsp <tr> <td align="center"> <b> user name: </ b> </ td> <td> <s: textfield name = "czyNumber" cssClass = "textstyle" theme = "simple" size = &q

  • Based on JDBC, JPA Annotation achieve simple CRUD Generic Dao

    The origin of ideas are pretty long history of reasons: [Use iBATIS history] The use of iBATIS has been a long time, the system is to use the CRUD template tool to generate the code, although there are tools to generate, but looked at a lot of CRUD the Sq

  • Hibernate secondary cache

    Hibernate cache: 2-bit cache, also known as process-level cache or SessionFactory level cache, secondary cache can be shared by all of the session Cache configuration and the use of: Will echcache.xml (the document code in hibernate package directory ...

  • The level Hibernate cache

    Hibernate cache level: (1) a cache is very short and the session life cycle consistent, also known as session-level cache-level cache or transaction-level cache (2) Ways of Supporting level cache: get (); load (); iterator (); only entity object cach ...

  • Hibernate's lazy strategy

    hibernate Lazy strategy can be used in: <class> tag, it can be true / false Tags can <PROPERTY> values true / false type of necessary tools to enhance <set> <list> can tag values true / false / extra <many-to-one> <on ...

  • Sign in spring struts2.0 hibernate user authentication

    Engage in a day has finally put the ghost of a user log in to engage in things out. . Ah first experience with a spring to manage the bean is a good tool. Of course, far more than this spring profound role in it. This is called a simple sense of the ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries