Hibernate delayed loading (difference between get and load), hibernateload

Source: Internet
Author: User

Hibernate delayed loading (difference between get and load), hibernateload
Summary:

In hibernate, we know that to get an object from the database, there are usually two methods, one is through session. get () method. The other method is through session. the load () method, and the two methods are actually different when getting an object, in terms of query performance.

Directory: load Method

When you use the load method to obtain an object, hibernate uses the delayed loading mechanism to load the object, that is, when we use session. when the load () method is used to load an object, no SQL statement is issued. The current object is actually a proxy object. This proxy object only saves the id value of the object, only when we want to use this object to obtain other attributes will we issue an SQL statement to query our objects from the database.

 

Session = HibernateUtil. openSession ();/** when loading objects through load, the delayed loading mechanism is used, and no SQL statement is issued at this time, the */User user = (User) session will be queried from the database only when we need to use it. load (User. class, 2 );

 

 

    

 

We can see that if we only load our User object through load, we will find that this object will not be queried from the database in the console, that is, no SQL statement will be issued, but if we want to use this object:

 

session = HibernateUtil.openSession();User user = (User)session.load(User.class, 2);System.out.println(user);

 

 

In this case, the console sends an SQL query statement to query the object from the database:

Hibernate: select user0_.id as id0_0_, user0_.username as username0_0_, user0_.password as password0_0_, user0_.born as born0_0_ from user user0_ where user0_.id=?User [id=2, username=aaa, password=111, born=2013-10-16 00:14:24.0]

 

At this time, we may think that, since the load method is called, no SQL statement is issued to find this object from the database, What is the object of this User object?

In fact, this User object is one of our proxy objects. This proxy object only saves the id attribute:

 

Session = HibernateUtil. openSession ();/** when an object is loaded using the load method, the delay loading mechanism is used. In this case, the User object obtained is actually a * proxy object, the proxy object only has the id attribute */User user User = (User) session. load (User. class, 2); System. out. println (user. getId (); console: 2

 

 

We can see that if we only print the id value of this user object, the console will print this id value, but it will not issue an SQL statement to query it from the database. This proves that our user object is only a proxy object that saves the id. But if I want to print other property values of the user object, will I issue an SQL statement at this time? The answer is yes:

 

Session = HibernateUtil. openSession ();/** when an object is loaded using the load method, the delay loading mechanism is used. In this case, the User object obtained is actually a * proxy object, the proxy object only has the id attribute */User user User = (User) session. load (User. class, 2); System. out. println (user. getId (); // if you want to obtain other user attributes, the System will be queried from the database. out. println (user. getUsername ());

 

 

Now let's look at the console output:

2Hibernate: select user0_.id as id0_0_, user0_.username as username0_0_, user0_.password as password0_0_, user0_.born as born0_0_ from user user0_ where user0_.id=?aaa

 

I believe that through the above examples, you should have a good understanding of the load object loading method.

Get Loading Method

Compared with the load delay loading method, get is much more direct, when we use session. when the get () method is used to obtain an object, no matter whether this object is used, an SQL statement is issued to query the object from the database:

 

Session = HibernateUtil. openSession ();/** when an object is loaded using the get method, an SQL statement is issued no matter this object is not used. query the object from the database */User user = (User) session. get (User. class, 2 );

 

  

In this case, we get the user object through the get method, but we didn't use it, but we found that the console will output the SQL query statement:

Hibernate: select user0_.id as id0_0_, user0_.username as username0_0_, user0_.password as password0_0_, user0_.born as born0_0_ from user user0_ where user0_.id=?

 

Therefore, we can see that the load loading method is better than the get loading method, because during load loading, all we get is a proxy object, when you really need to use this object, you can query it from the database.

Some minor issues when using get and load

After learning about the load and get loading mechanisms, let's take a look at some minor issues that may occur in these two methods:

① If we use the get method to load objects, when we try to get an object whose id does not exist, an NullPointException exception will be reported.

 

Session = HibernateUtil. openSession ();/** when you try to get a user object whose id does not exist in the get method, an NullPointException exception */User user = (User) session is reported. get (User. class, 20); System. out. println (user. getUsername ());

 

In this case, we can view the output information of the console and report the NULL pointer exception:

Hibernate: select user0_.id as id0_0_, user0_.username as username0_0_, user0_.password as password0_0_, user0_.born as born0_0_ from user user0_ where user0_.id=?java.lang.NullPointerException  .........

This is because the get method is used to query the object in the database, but the id value does not exist. Therefore, if the user object is null, an NullPointException exception is reported.

② If we use the load method to load objects, when we try to get an object whose id does not exist, the ObjectNotFoundException exception will be reported:

 

Session = HibernateUtil. openSession ();/** when you try to get a user object whose id does not exist in the get method, ObjectNotFoundException exception */User user = (User) session is reported. load (User. class, 20); System. out. println (user. getId (); System. out. println (user. getUsername ());

 

Let's take a look at the console output:

20Hibernate: select user0_.id as id0_0_, user0_.username as username0_0_, user0_.password as password0_0_, user0_.born as born0_0_ from user user0_ where user0_.id=?org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.xiaoluo.bean.User#20]......

Why is an exception reported when a non-existent object is obtained using the load and get methods ?? This is because of the load delay loading mechanism. When load is used, the user object is a proxy object and only the current id value is saved, when we try to get the username attribute of this object, this attribute does not actually exist, so the ObjectNotFoundException exception will be reported.

③ Org. hibernate. LazyInitializationException

Next, let's look at an example:

public class UserDAO{    public User loadUser(int id)    {        Session session = null;        Transaction tx = null;        User user =  null;        try        {            session = HibernateUtil.openSession();            tx = session.beginTransaction();            user = (User)session.load(User.class, 1);            tx.commit();        }        catch (Exception e)        {            e.printStackTrace();            tx.rollback();        }        finally        {            HibernateUtil.close(session);        }        return user;    }}

 

  @Test    public void testLazy06()    {        UserDAO userDAO = new UserDAO();        User user = userDAO.loadUser(2);        System.out.println(user);    }

 

Simulate an object such as UserDAO, and load an object in the test case. At this time, we find that the console reports a LazyInitializationException.

org.hibernate.LazyInitializationException: could not initialize proxy - no Session  .............

 

What is the cause of this exception ?? Because of the load delay loading mechanism, when we load an object through the load () method, no SQL statement is issued to query the object from the database, this object is only an id-only proxy object. We have not used this object yet, but our session has been closed, so when we use this object in the test case, the exception LazyInitializationException will be reported.

Therefore, if we see the exception LazyInitializationException reported on the console, we will know that the load method is used to delay loading an object. There are two ways to solve this problem, one is to change load to get the object, and the other is to enable and disable the session in the presentation layer.

 

So far, the get and load methods of hibernate have been analyzed !!!

 

Article from:

Http://www.cnblogs.com/xiaoluo501395377/p/3371776.html

Related Article

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.