Hibernate lazy loading

2010-05-10  来源:本站原创  分类:Java  人气:343 

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.

相关文章
  • hibernate lazy loading principles reproduced great ~ ~ 2008-11-12

    hibernate lazy loading of the principle of When using the load method of query session records in the database, we return a proxy object, rather than the needs of that object; for example, there is a Student table in the database, we have cn.binyulan

  • Hibernate Lazy loading not fully realized due to OO 2010-06-02

    Transfer from: http://www.sulong.info/archives/335 Object and relational database fundamental difference exists between, ORM (object / relational mapping) tried to object mapping to relational database table structure, which simplifies storage object

  • Discussion hibernate lazy loading 2010-10-01

    Hibernate lazy initialization error is the use of development projects in the most common mistakes. If the configuration of a class or collection of search strategy of delay, it must be when the agent or agent class instance is a collection of persis

  • json-lib hibernate lazy loading problem 2010-10-07

    json-lib hibernate lazy loading problem ------ Question: Using json-lib to hibernate lazy loading of objects into a json when session closed packet error ------ Address: Can use json-lib's JsonConfig filter out unwanted properties, using the apply me

  • hibernate lazy loading issue a temporary solution 2011-05-06

    hibernate lazy loading problems often plague us today, hibernate itself found to provide some solutions Hibernate.initialize (company.getUsers ()); This collection is loaded users But does not support recursive loading it is not guaranteed that the e

  • Hibernate lazy loading mechanism 2009-09-18

    Lazy loading: Lazy loading mechanism is in order to avoid unnecessary performance overhead and put forward the so-called lazy loading is that when data in the real needs when we come to the real implementation of the data load operation. Provided in

  • hibernate lazy loading failed 2010-02-03

    Concerned about the javaeye has been more than a year, but had no opportunity to write a log. Today, they wanted big cow jokes are not afraid of you wrote a log. Want to beginners strtus, hibernate, spring who have some help. The lazy loading, I no l

  • BlazeDS & Hibernate lazy loading in n-tier arhitecture 2010-04-07

    Original link: http://forum.springsource.org/showthread.php?t=71622 Hi, We have faced an issue on lazy loading Domain Objects with Hibernate in n-tier architecture with Spring BlazeDS. Our architecture is just a basic Spring architecture model: - Fle

  • Hibernate lazy loading FOR Class 2010-05-09

    lazy Policy can be used in : * <class> The label : Can the value true/false * <property> The label, you can value true/false, This feature requires class enhancement * <set>/<list> And so the collection, you can evaluate to true/fa

  • Hibernate lazy loading FOR Connection 2010-05-10

    Hibernate Collection property of lazy loading policy : In the collection properties, you can configure the lazy loading policy , A value of :true/false/extra true: The default value, which means that only the collection gets inside the element object

  • Hibernate lazy loading single-ended correlation FOR 2010-05-10

    Hibernate To load policy-Terminal associated lazy : That is, in <one-to-one>/<many-to-one> You can configure on the label Lazy loading policy . Can a value :false/proxy/no-proxy false: Cancel the lazy loading policy, that is, while loading the

  • Hibernate lazy loading 2010-05-10

    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 t

  • Hibernate lazy loading in the load method and the principle of 2010-08-29

    When using the session method in load record in the database query, we return a proxy object, not really need that object; for example, there is a Student table in the database, we have cn.binyulan.doman.Student areas object, if the query Id is "2006

  • Detailed hibernate lazy loading problem 2010-10-03

    Lazy loading: Lazy loading mechanism is to avoid unnecessary performance overhead of their argument, the so-called lazy loading is when the really need the data before it will actually perform the data loading operation. Provided in the Hibernate obj

  • Hibernate lazy loading simple solution 2010-10-03

    Recently doing a project with a piece of data persistence layer hibernate. After the previous study used no how, has been in use IBATIS. When the integration of spring security encountered "no session, or session was closed", so look for good so

  • spring + hibernate lazy loading errors integrated solution 2010-11-25

    org.springframework.dao.InvalidDataAccessApiUsageException error org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.NEVER / MANUAL): Turn your Session into FlushMode.COMMIT / AUTO

  • The hibernate lazy loading (Lazy Loading) 2011-01-07

    Avoid some cases, association brings unnecessary overhead, Hibernate introduced the concept of lazy loading; Hibernate3, can be recorded for the delay: Entity object Collection (Collection) Lazy property Through the Load method, the target entity obj

  • Spring + Hibernate lazy loading test base class 2009-08-13

    package cn.com.oneslife; import junit.framework.TestCase; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.junit.AfterClass; import org.springframework.context.ApplicationContext; import org.springframework.context.suppor

  • hibernate lazy loading Principle and Realization 2010-03-29

    Can read: http://superleo.javaeye.com/blog/243322

  • hibernate in the pessimistic and optimistic locking lock and lazy loading 2009-04-02

    hibernate frequently used when many individuals of the same data at the same time when changes will happen dirty data, resulting in data inconsistency, the solution can be adopted by the pessimistic and optimistic locking to achieve lock. Pessimistic