The Get () and load () methods in Hibernateibernate

Source: Internet
Author: User

In hibernate we know that if we want to get an object from the database, there are usually two ways, one is through the Session.get () method, the other is through the Session.load () method, and then actually the two methods are different when acquiring an entity object. The two are different in query performance.

I. Load loading mode

When using the Load method to get an object, Hibernate uses the mechanism of lazy loading to load the object, that is, when we use the Session.load () method to load an object, the SQL statement is not emitted at this time, and the currently obtained object is actually a proxy object , this proxy object only holds the ID value of the Entity object, and only when we want to use this object to get other properties, we will issue the SQL statement to query our object from the database.

Session = Hibernateutil.opensession ();            /             * * When loading an object by load, the lazy load mechanism is used, and the SQL statement is not issued at this time, and is only queried from the database when we need to use *            /user user = (user) Session.load ( User.class, 2);

We see that if we simply load our user object through load, from the console we will find that the object is not queried from the database, that is, the SQL statement is not emitted, but if we want to use the object:

Session = Hibernateutil.opensession ();      User user = (user) session.load (user.class, 2); SYSTEM.OUT.PRINTLN (user);

At this point we see the SQL query statement issued by the console that will 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 Bo rn0_0_ from user user0_ where user0_.id=? User [id=2, Username=aaa, password=111, born=2013-10-16 00:14:24.0]

At this point we might think that since the load method is called, the SQL statement is not emitted to isolate the object from the database, so what exactly is the user object?

In fact, this user object is one of our proxy objects, this proxy object only holds the id attribute:

Session = Hibernateutil.opensession ();            /             * * When loading an object by load, a lazy load mechanism is used, and the resulting User object is actually a             * proxy object with only the id attribute in the proxy object             *            /user user = (user) Session.load (User.class, 2);            System.out.println (User.getid ());

Console:2

We see that if we only print out the ID value of the User object, the console prints out the ID value, but the same does not emit a SQL statement to query from the database. This confirms that our user object is just a proxy object that holds the ID, but if I need to print out other property values for the user object, will this time issue an SQL statement? The answer is yes:

            Session = Hibernateutil.opensession ();            /             * * When loading an object by load, a lazy load mechanism is used, and the resulting User object is actually a             * proxy object with only the id attribute in the proxy object             *            /user user = (user) Session.load (User.class, 2);            System.out.println (User.getid ());            If you want to get other user properties at this point,            System.out.println (User.getusername ()) is queried from the database.            

At this point we look at the output of the console:

2hibernate:select user0_.id as id0_0_, user0_.username as username0_0_, User0_.password as password0_0_, User0_.born as B orn0_0_ from user user0_ where user0_.id=?aaa

I believe that through the above examples, you should have a good understanding of the load of this loading object of the way it is.

Second, get load mode

The get is much more straightforward than load's lazy loading, and when we use the Session.get () method to get an object, regardless of whether we make the object non-use, the SQL statement is issued to query the database:

Session = Hibernateutil.opensession ();            /             * * When loading an object by the Get method, the SQL statement is issued, regardless of the object being used, from the database             */            User user = (user) Session.get (user.class, 2);

At this point we get the user object by get, but we don't use it, but we find that the console will output SQL query statements:

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

So we can see that the load mode using load is better than the load mode of GET, because when load is loaded, it is just a proxy object that is queried from the database when it is really necessary to use this object.

Iii. some minor issues when using GET and load

When we understand the load mechanism of load and get, let's take a look at some of the minor issues that arise in both ways:

① if a Get method is used to load an object, the nullpointexception exception is reported when we try to get an object with an ID that does not exist.

        Session = Hibernateutil.opensession ();             /* * When attempting to get a User object with an ID that does not exist through get, the nullpointexception exception is reported at this time             *            /user user = (user) Session.get (user.class, );            System.out.println (User.getusername ());

At this point we look at the output information of the console and will report the exception of the null pointer:

Hibernate:select user0_.id as id0_0_, user0_.username as username0_0_, User0_.password as password0_0_, User0_.born as Bo rn0_0_ from user user0_ where user0_.id=?java.lang.nullpointerexception ....

This is because we will go to the database through the Get method to query the object, but this ID value does not exist, so at this time the user object is null, so it will be reported nullpointexception exception.

② If you load an object using load mode, when we try to get an object with an ID that does not exist, the objectnotfoundexception exception is reported:

Session = Hibernateutil.opensession ();             /* * When attempting to get a User object with an ID that does not exist through get, the objectnotfoundexception exception is reported at this time             *            /user user = (user) Session.load ( User.class, ();            System.out.println (User.getid ());            System.out.println (User.getusername ());

Let's look at the output of the console:

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 it different from using the Load method to get a non-existent object in the same way as get?? The reason for this is because of the load delay loading mechanism, when using load, the user object at this time is a proxy object, just save the current ID value, when we try to get the object's Username property, this property is actually nonexistent, So I will report objectnotfoundexception this anomaly.

③org.hibernate.lazyinitializationexception exception

Now 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);    }

Simulates an object like Userdao, and then we load an object through load in a test case, and we find that the console will report an lazyinitializationexception exception

Org.hibernate.LazyInitializationException:could not initialize Proxy-no Session .......

What is the reason for this anomaly?? Or because of the lazy load mechanism of load, when we load an object through the load () method, there is no SQL statement to query the object from the database, the object is just an ID proxy object, and we are not using that object. But at this point our session is closed, so when we use the object in the test case we will report lazyinitializationexception this exception.

So later we just see the console report lazyinitializationexception this exception, we know that the load is used to delay the loading of an object, there are two ways to solve this, one is to change the load to get the way to get the object, The other is to open our session and close the session in the presentation layer.

The Get () and load () methods in Hibernateibernate

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.