Hibernate lazy loading

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.

分类:Java 时间:2010-05-10 人气:341
分享到:
blog comments powered by Disqus

相关文章

  • C Language System Resource Control (getrlimit & & setrlimit) 2010-03-26

    C Language System Resource Control (getrlimit & & setrlimit) 2007-08-17 00:40 Each process has its own set of resource constraints, the (*) inux system, we can # Include <sys/resource.h> int getrlimit (int resource, struct rlimit * rlim); in

  • sql date have been part of the current system time 2010-11-19

    sql date have been part of the current system time CONVERT (varchar (10), getDate (), 120) To attain "Yesterday, today," the SQL date functions Categories: MS-SQL Server base class -------------------------------------------------- -------------

  • Turn: SQL Server Setup was unable to obtain system account information for the ASPNET account | | Solutions 2011-07-05

    Title: Microsoft SQL Server Setup ------------------------------ SQL Server Setup can not obtain system account information for the ASPNET account. To continue, please reinstall. NET Framework, and then run SQL Server Setup again. For help, click: ht

  • SQL foreign key relationship and explain the options when 2011-07-27

    Child table, parent table definition: tables with foreign key is the child. Primary key is another table referenced table is the parent table. In other words: Because the identity of the parent table is a lot of sub-records in the table reference, it

  • sql copy tables and table structure 2010-04-12

    Review the time to see the contents of the sql: 1. Copy Table (1) create a new table, copy the table structure and copy the contents of the table create tablenew select * from tableold (2) Create a new table, copy the table structure but does not cop

  • Replication of SQL Server tables data development SQL script generator 2010-06-02

    Replication of SQL Server Developer SQL script generates the table data uses SQL Server 2000 comes with a "generate SQL script" tool, you can generate to create tables, views, stored procedures, etc. SQL script. So, can the table data as SQL scr

  • PL / SQL data tables into 2010-06-20

    Today, because of certain reasons so, uninstall the Oracle database, export database before unloading the table, since we will install the database, then the troubles in the province to re-build the table, but when you import the table reported insuf

  • sql server2005 tables export data - stored procedure 2010-12-21

    Create the stored procedure: The following stored procedure code: CREATE PROCEDURE dbo.UspOutputData @ Tablename sysname AS declare @ column varchar (1000) declare @ columndata varchar (1000) declare @ sql varchar (4000) declare @ xtype tinyint decla

  • Knowledge summary judgments sql database, tables, columns, the existence of 2011-05-17

    To determine the name of the current database Code: DECLARE @ maDbName SYSNAME IF (DB_NAME () LIKE N '% Test') BEGIN SET @ maDbName = N'MemberArchiveTest ' END ELSE BEGIN SET @ maDbName = N'MemberArchive ' END Code Interpretation: If the test at the

  • BSEG and BSIS.BSAS.BSID.BSAD.BSIK.BSAK six tables relationship 2011-05-26

    BSAS + BSIS + BSAK + BSIK + BSAD + BSID = BSEG cleared │ opened -------------------------------- BSAS │ BSIS ==> all GL documents BSAK │ BSIK ==> all AP documents BSAD │ BSID ==> all AR documents BKPF the financial document header, BSEG is a fina

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.252 (s). 12 q(s)