Hibernate lazy loading

sponsored links
What is hibernate lazy load? The so-called lazy loading (lazy) is to delay loading, lazy loading.
When to use lazy loading it? Can only be answered when to use lazy loading with lazy loading.
Why should lazy load it? When we want to access the data too large, it evidently is not appropriate to use the cache because of memory capacity is limited, in order to reduce concurrency and reduce system resource consumption, we let the data is loaded only when needed, then we to use a lazy load.

Such as departments and staff PO PO, departments and employees more than one pair, if lazy is set to false, as long as the load of a department of po, will be configured according to one to many relationship between the po all staff have loaded up. But in fact sometimes just need to use the information sector, employees do not use the information, then add staff po is equivalent to waste of resources. If lazy is set to true, then only when you visit the department po employee information when it is loaded back to the staff po information.
Hibernate 3.0 in the lazy three values: true, false, proxy, the default is lazy = "proxy".
What specific set of needs to look at business, not to say which set is the best, to how low to set depends on your actual needs.

If the student objects in the object contains a head:
1. If you determine when an object with a student should use head object in the property, then you set the load immediately, because the setting load it immediately, while student in the query will check student's head, hibernate will be in When the query associated with two tables to generate the sql may be only one.
2. If you set the delay in loading, then certainly to generate 1 + N clause sql statement: The "1" is the student's statement query, "N" is the student's id under the N-N-head to check the statement . Moreover, the delay in loading time is only going to use to execute the query, so the system determine where to load, there's nothing to load takes time, performance, certainly not as good as immediately loaded.
3. If some areas need to use student when it is used in head properties, then you are set to delay load, because it is two tables of data, certainly better than the data query a table large consumption.

Delay in loading mechanism is to avoid unnecessary performance overhead of their argument, the so-called delay loading is that when the data in real need, when really the implementation of the data load operation. Provided in the Hibernate entity objects and lazy loading on the collection of delay, while in Hibernate3 also provides property lazy.

A physical object delay load <br /> If you want to use delay loading entity object must be in the physical mapping configuration file for the appropriate configuration, as follows:
<hibernate-mapping>
        <class name="com.mixele.entity.User" table="user" lazy="true">
                ......
        </class>
</hibernate-mapping>

By class of lazy attribute set to true, to open the physical characteristics of the delayed load. If we run the following code:
User user=(User)session.load(User.class,"1");//(1) Here  load() Method returns the User object proxy class object  
System.out.println(user.getName());//(2) Through the CGLIB given an assignment to the callback mechanism  

When running to (1) Office hours, Hibernate does not initiate a data query, if this time through a number of debugging tools, observe the user object then the memory snapshot will be surprised to find, then return may be User $ EnhancerByCGLIB $ $ bede8986 types of objects and their attributes as null. This is how it? session.load () method returns the entity object's proxy class object, the object here to return User object type is a proxy class object. In Hibernate by using CGLIB, to construct a target 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. Displayed by the debugger memory snapshot, you can see real time User objects, is included in the proxy object CGLIB $ CALBACK_0.target properties.
When running to (2) Department, the then called user.getName () method, when given by CGLIB callback mechanism, in fact, called CGLIB $ CALBACK_0.getName () method, when you call the method, Hibernate will first Check CGLIB $ CALBACK_0.target property is null, if not empty, then call the target object's getName method, if empty, will be launching a database query to generate SQL statement like this: select * from user where; to query data and construct the target object, and assign it to the CGLIB $ CALBACK_0.target properties.
This, through an intermediate proxy object, Hibernate implementation of the entity's delay in loading, only when users actually initiated the action was when the entity object attribute, it really will mount the database query operation. Therefore, the delayed entity loading is completed by the middle of the proxy class, so only session.load () method will delay use of physical load, as only session.load () method will return the entity classes in the proxy class object.

Lazy type B collection
In Hibernate's lazy loading mechanism for the collection types of applications, meaning the most significant, because it might make the performance is greatly improved, this Hibernate done a lot of efforts, including JDK Collection of independent Shixian In many relationships, the definition used to hold a collection of related object of Set is not java.util.Set type or subtype, but net.sf.hibernate.collection.Set type, by using a custom collection class implementation, Hibernate collection type implements lazy. To set the type to use delay loading, you must configure the following entities associated with the part about the class:
<hibernate-mapping>
        <class name="com.mixele.entity.User" table="user">
                ......
                <set name="addresses" table="address" lazy="true" inverse="true">
                        <key column="user_id"/>
                        <one-to-many/>
                </set>
        </class>
</hibernate-mapping>


By <set> element lazy attribute set to true to open the collection type of delay in loading characteristics. See the following code:
User user=(User)session.load(User.class,"1");
Collection addset=user.getAddresses();//(1) And will not be launched on the associated data query to load the associated data  
Iterator it=addset.iterator();//(2) Find qualified entity object  
while(it.hasNext()) {
        Address address=(Address)it.next();
        System.out.println(address.getAddress());
}

When the program execution to (1) Department, we will not launch on the associated data query to load the associated data, only to run into (2) Department, the real data read operation will start, then Hibernate will be based cache qualified data in the index, to find qualified entity object.
Here introduces a new concept - the data index, the following will first explain what is the data index. On collection types in Hibernate cache, the cache is divided into two parts, the first collection of all entities in the cache id list, and then cached entity object, the object id list of these entities, the so-called indexing. When the index to find data, if not find the corresponding data index, then it will execute a select SQL statement, access to qualified data, and construct a collection of physical objects and the data index, and then return a collection of physical objects and the entity object and data into an index into the cache of Hibernate. On the other hand, if the index to find the corresponding data, remove the id from the data in the index list, and then find the corresponding id in the entity cache, if found return from the cache, if not found, in initiating select SQL query. Here we see another issue that may affect performance, which is a collection of types of caching strategies. If the following configuration collection type:
<hibernate-mapping>
        <class name="com.mixele.entity.User" table="user">
                ......
                <set name="addresses" table="address" lazy="true" inverse="true">
                        <cache usage="read-only"/>    <!-- Only the data to the index cache  -->
                        <key column="user_id"/>
                        <one-to-many/>
                </set>
        </class>
</hibernate-mapping>

Here applied <cache usage="read-only"/> configuration, if we adopt this strategy to configure the collection type, Hibernate will only cache of the data index, not the entity object will be set in the cache. As configured to run the following code:
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());
}

Run this code, the output will be similar to the following:
Select * from user where;
Select * from address where user_id = '1 ';
Tianjin
Dalian
Second query ... ...
Select * from address where;
Select * from address where;
Tianjin
Dalian
Can see that when the second query is executed, the implementation of the two pairs of address table query, why is it so? This is because when the first load entities, the According to the collection type caching strategy Pei Zhi, Zhi Jin Hang the collection data index the cache and are not on the collection in the entities Duixiang cache, Suo Yi in the second re-load the entity O'clock , Hibernate entities to find the corresponding data index, but according to data indexing, but can not be found in the cache corresponding to the entity, Hibernate data according to the index was launched to find two select SQL in the query, where the performance caused by the waste How can we avoid this situation? Collection must also specify the type of entity cache strategies, on the set of types of configuration:
<hibernate-mapping>
        <class name="com.mixele.entity.User" table="user">
                ......
                <set name="addresses" table="address" lazy="true" inverse="true">
                        <cache usage="read-write"/>
                        <key column="user_id"/>
                        <one-to-many/>
                </set>
        </class>
</hibernate-mapping>

Hibernate will then set the type of entities to the cache, re-run the above code, the output will be similar to the following:
Select * from user where;
Select * from address where user_id = '1 ';
Tianjin
Dalian
Second query ... ...
Tianjin
Dalian
At this time there will not be indexed according to the data query of SQL statements, because at this time can be obtained directly from the cache stored in a collection of entity object types.

C Properties lazy <br /> in Hibernate3, the introduction of a new feature - attribute the delay to load, this mechanism has to provide access to high-performance query a powerful tool. When reading a large data object, assuming that the User object has a resume in the field, the field is a java.sql.Clob type of resume that contains the user's information, when loading the object, have each time To load this field, regardless of whether we really need it, and this large data objects will be great to read their own performance overhead. In Hibernate2 in size only by the performance-oriented segment, to break down the User class, to solve this problem, but in Hibernate3, you can delay loading mechanism via the property to give us only when we really need the word operation period of time, only to read the field data the ability to configure the entity class must therefore be as follows:
<hibernate-mapping>
        <class name="com.mixele.entity.User" table="user">
                ......
                <property name="resume" type="java.sql.Clob" column="resume" lazy="true"/>
        </class>
</hibernate-mapping>

Lazy by <property> element attribute property is set true to open the delayed loading, in Hibernate3 in order to achieve the lazy attribute, use the class enhancer to the Class of the entity class file for enhanced treatment, by enhancing device enhanced CGLIB callback mechanism to logic, adding an entity class, where we can see that attribute the delay to load, or through CGLIB to achieve. CGLIB is an open source Apache project, the java class library to manipulate the byte code, byte code to dynamically constructed according to meet the requirements of the class object. According to the above configuration we run the following code:
String sql="from User user where user.name='zx'";
Query query=session.createQuery(sql); //(1)Select id,age,name from user where name='zx';
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)Select resume from user where;
}

When the Executive to (a) Department, the following will generate similar SQL statement:
Select id, age, name from user where name = 'zx';
Hibernate will then retrieve the User entity in all non-lazy properties of the corresponding field data, when the Executive to (2) Department, it will generate the following SQL statement like: Select resume from user where;
Then will mount a real resume field data read operation.
Hibernate provides a lazy load strategy, with the open session in view when the load can be avoided without the need related objects.
The problem is many cases, the same object may need to use different occasions, some situations may need to load all of the relations between one-time object. For example, in the user log on, you need time to obtain all the associated user object, the user CRUD operations, you need to load as much as possible to avoid the need to use lazy loading objects.
Can be lazy set to true, to provide for logon request a different interface to solve the above problem, but if the system exists in a lot of this situation, what better way to solve it? As long as you use the Spring, if the issue does not involve long-range, OpenSessionView can be resolved.
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Hibernate lazy loading

  • Shi means small, so that HIBERNATE support for the standard deviation of the variance function of MYSQL

    Open-source category org.hibernate.dialect.MySQLDialect In the constructor to include two lines of code registerFunction ( "variance", new StandardSQLFunction ( "variance", Hibernate.DOUBLE)); registerFunction ( "stddev" ...

  • tomcat6.0 + myeclipse6.5 under tomcat data source configuration

    (1) Environment: such as a very important question! Different environment, different configurations! (2) struts package loaded: My MyEclipse6.5 bring him under the load of the struts jar package Error occurred "collections can not find under qui ...

  • Great Design

    Understand the principle with the practice, details the relationship between thought, we'll go have selectively study the details, we must work on the details because the details are important to you to use the technical details of implementation ...

  • SqlServer database connection pool to connect tomcat

    First, install the JDBC Driver The database driver jar file to put (Tomcat_install) \ common \ lib directory Second, configure the Connection Pool 1. Overall connection pool configuration, Tomcat in any Web application can be configured to use the co ...

  • hibernate the third study (mapping file configuration)

    If you do not want to use the default hibernate.cfg.xml file as a configuration file, we can also specify the configuration file name: File file = new File ( "C: \ \ myhibernate.xml"); Configuration config = new Configuration (). Configure (file

  • Hibernate in the inverse and cascade

    First of all, to quote another blog saying: 1.cascade ="..."? cascade is not a property of many-to-many relationship must have it just so that we insert or delete at the time like some more convenient, as long as the source of the cascade insert

  • How the primary key agent-hibernate

    Existing Table A, B Statement: A, B field id-based keys. A: [id, name] B: [id, Aid, title] B and A's set up a many-to-one relationship because of A, B two tables are the primary key id field so add B when Hibernate will automatically retrieve id ...

  • 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

  • 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 ...

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