Hibernate lazy Load Detailed

Source: Internet
Author: User



Lazy Load Detailed

Lazy loading for Hibernate is one of the most common features, the following is a detailed understanding of the principle of lazy loading and considerations

lazy Load principle of load () method

In hibernate, there are two query methods, respectively, get () and load (), and the difference is that load () has lazy loading features. The Load () method does not return the data directly to a specified object when querying a particular piece of data, but instead accesses the database and obtains the data when you really need to use some of the attributes in the object. His advantage is that it reduces the process itself because of the slowness of processing caused by frequent interaction with the database.

As an example of a person class, the way we write a query is as follows:

public static void query (int id) {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 to the Hibernate configuration file

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


The effect of this property is to print every SQL statement generated by the Hibernate runtime

After running the above method, we do not see hibernate print any query statements, then we can return the statement of the comment, let him print the query to the name of person. At this point we can see the query statement generated by hibernate and see the person's Name property. This is lazy to load up.

So when the hibernate lazy load, the returned object is empty. The answer is no, we can print the Person.getclass () method to verify that the printed result is not NULL, but a person with a bunch of strange characters after the class. To be sure, lazy objects are not empty, and the object's type is not the person class. So what is he anyway?

In fact, this cash we call it the proxy object, and this object belongs to the class is a subclass of the person class, is a hibernate automatic implementation of a subclass. 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 relationship mapping.

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

public static person query (int id) {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 ();
            }
        }
        return person;
    }


Calling this method and returning the queried proxy object, we can print the object's Name property after returning the object, and then throw a Org.hibernate.LazyInitializationException exception

This is lazy. Loading cannot initialize an exception, which illustrates one thing, lazy load if you want to query the database through the proxy object, you need to be able to do so before the session closes. However, if the proxy object is to be used again after the session is closed, a method initialize () that initializes the proxy object is defined in hibernate to initialize 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 initialize 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 open, we will analyze the lazy load according to different situations.

a one-to-one lazy load analysis

A one-to-one lazy load is not commonly used, because lazy loading is designed to reduce the interaction with the database and thus improve execution efficiency, in a one-to-one relationship, each data in the primary table will not increase the cost of interaction from a single database in the table, even if it is queried, and the primary table cannot have contrained= True, so the primary table is not lazy to load. (Can be from a table)

Note: Lazy loading is invalidated when the fetch is set to join. Because the fetch works as a crawl, he has two values for select and join, and the default is select. That is, when set to join, he queries the table information directly to join instead of using the select query again, causing lazy loading to expire.

Lazy Loading analysis of one-to-many and multi-pairs

Unlike a one-to-one association, with One-to-many and one-to-many associations, each attribute of the primary table will be a lot of data from the table, which is very effective when lazy loading. For example, a department has more than one employee, if not lazy load, every query this department will query out multiple employees, which will greatly increase the cost of interacting with the database. So hbernate the default is to join lazy load. This is why a persistentindexed* type object is returned when querying collection properties. The object is actually a proxy object. Of course, you can disable it in the mapping file by setting the Lazy property to false.

multi-pair lazy loading analysis

Although many pairs of one is the same as the one-to-one relationship, but in Hibernate, the default is lazy loading. Another point to note is that lazy loading does not distinguish between the collection properties of whether there is a value, even if there is no value, he will still use lazy load, which is lazy loading is not perfect one of the places.

 

lazy Load Some details to expand

In some cases, we still need to use lazy to load the proxy object to query the database, then we need to initialize the proxy object, but the problem is, when we can not determine the initialization after the use of the object will do, so it is not wasted resources. 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 argument to False. But there are drawbacks, 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 less effective.

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.