Hibernate lazy Loading (reprint)

Source: Internet
Author: User

http://blog.csdn.net/sanjy523892105/article/details/7071139

Lazy Loading Detailed

Lazy loading is one of the more commonly used features in Hibernate, so let's look at the principles and considerations for lazy loading below.

Lazy load principle of the load () method

In hibernate, there are two query methods, namely get () and load (), and the difference between the two methods is that load () has lazy loading characteristics. The Load () method does not directly return the data in the form of a specified object when querying a certain piece of data, but only accesses the database and obtains the data when you really need to use some of the properties of the object. His advantage is that the process itself can be reduced because of the slow processing caused by frequent interactions with the database.

As an example of a person class, we write a query in the following way:

 Public Static voidQueryintID) {Session Session=NULL; Try{Session=hibernateutil.getsession (); Person Person= (person) session.load (person).class, id); //System.out.println (Person.getname ()); }Catch(Hibernateexceptionex) {ex.printstacktrace (); }finally{              if(session!=NULL) {session.close (); }          }      }  

Then add the following properties in the Hibernate configuration file

<name= "Hibernate.show_sql">true</ Property >  

This property is useful for printing every SQL statement produced by Hibernate runtime

After running the above method, we did not see Hibernate print any query statement, then we can re-adjust the comment statement back, let him print the name of the person queried. At this point we can see the query statement produced by Hibernate and see the Name property of the person. This is lazy loading.

So when hibernate lazily loads, is the object returned empty? The answer is no, we can verify by printing the Person.getclass () method that the printed result is not NULL, but rather a class that adds a bunch of strange characters to the person behind it. It is certain that lazy-loaded objects are not empty, and that the object's type is not the person class. So what is he exactly?

In fact, this is what we call a proxy object, and the class that this object belongs to is a subclass of the person class, which is a subclass of hibernate auto-implementation. This subclass is characterized by the fact that when you access a property of a person object, he automatically queries the data in the database for that object and returns it, which is why the entity class cannot be the final type when creating an object-relational mapping.

But this object has a life cycle, and we can rewrite the above method as follows:

 Public StaticPerson Query (intID) {Session Session=NULL; Person Person=NULL; Try{Session=hibernateutil.getsession (); person= (person) session.load (person).class, id); //System.out.println (Person.getname ()); }Catch(Hibernateexceptionex) {ex.printstacktrace (); }finally{              if(session!=NULL) {session.close (); }          }          returnPerson ; }  

Calling this method and returning the query to the proxy object, we can print the object's Name property after returning the object, throwing a org.hibernate.LazyInitializationException exception

This is lazy loading can not initialize the exception, this shows one thing, lazy loading if you want to query the database through the proxy object, you need to be closed before the session. However, if you must use the proxy object after the session is closed, hibernate defines a method initialize () that initializes the proxy object, which initializes the proxy object.

Note: When you use the GetID () method and the GetClass () method of the proxy object, you do not throw an exception that cannot be initialized because the two properties do not use the query database.

Lazy loading can be used for relational mapping and collection properties, and lazy loading can be closed and opened, and we will analyze lazy loading according to different situations.

One-on-one lazy load analysis

Lazy loading is not often a one-to-one, because lazy loading is designed to reduce the interaction with the database and thus improve execution efficiency, while in a single relationship, each data in the primary table is only for a database from the table, even if the query does not increase the cost of the interaction, and the main table cannot have contrained= True, so the primary table is not lazy to load. (Can have from a table)

Note: Lazy loading is invalidated when fetch is set to join. Since fetch is a fetch, he has two values to ask Select and join, and the default value is select. That is, when set to join, he will directly query from the table information to join instead of using the Select query again, resulting in lazy load invalidation.

One-to-many and many-to-many lazy load analysis

Unlike a one-to-one association, a single-to-many and a-to-many association, each property of the main table will have multiple data from the table, and lazy loading is very effective at this time. For example, a department has a number of employees, if not lazy loading, each query this department will query out multiple employees, which will greatly increase the cost of interaction with the database. So hbernate default is to join lazy loading. This is why a persistentindexed* type object is returned when the collection property is queried. The object is actually a proxy object. Of course, you can disable it in the mapping file by setting the Lazy property to false.

Lazy load analysis for many-to-one

While many-to-one relationships are the same, in hibernate, lazy loading is the default. It is also important to note that lazy loading does not distinguish whether there is a value in the collection attribute, even if there is no value, he will still use lazy loading, which is lazy loading is not perfect one of the places.

Lazy loading with some detail extensions

Sometimes, we still need to use lazy loaded proxy object to query the database when the session is closed, but we need to initialize the proxy object, but the problem is, when we are not sure how to use the object after initialization, so it is not wasted resources in vain? We can add a Boolean parameter to the method that uses the proxy object, so that when we don't need to initialize the proxy object, we just set the Boolean parameter to False. But there are shortcomings, because in the call, especially when others use, the more parameters, the method of learning costs will increase, so please discretion.

Lazy loading can also be used for some simple properties, but it is not recommended because it is more complex to implement and the effect is not obvious.

Hibernate lazy Loading (reprint)

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.