Things to note in "Hibernate" Hibernate using lazy loading

Source: Internet
Author: User

1, Introduction

When using some query methods, the method executes, but does not immediately send an SQL statement to query the database. Instead, the SQL execution load object data is triggered when the object's GetXXX method is accessed. This mechanism is called lazy loading.

2, advantages

Lazy loading is primarily provided for subsequent association mappings, and avoids finding useless associated data.
You can reduce the concurrency rate of database operations and increase memory resource usage.

3, using

In struts2, this mechanism is used by session.load () and Query.iterator ().

The following example uses the Session.load () method:

Hibernate.cfg.xml file

<?xml version= ' 1.0 ' encoding= ' UTF-8 '? ><! DOCTYPE hibernate-Configuration Public"-//hibernate/hibernate Configuration DTD 3.0//en" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.                   DTD ><!--Generated by MyEclipse Hibernate Tools. -->Org.hibernate.dialect.MySQLDialect</property> <property name= "Connection.url" >Jdbc:mysql://Localhost:3306/test?useunicode=true&amp;characterencoding=utf8</property> <property name= "Connection.username" >root</property> <property name= "Connec Tion.password ">517839</property> <property name=" Connection.driver_class ">Com.mysql.jdbc.Driver</property> <property name= "Show_sql" >true</property> <property name= "Format_sql" >true</property> <!--Load Mapping description information-<mappingclass= "Cn.test.bean.User"/> </session-factory>Hibernate.cfg.xml

On the inside specifies the print SQL execution log on the console

User.java file

 PackageCn.test.bean;ImportJavax.persistence.Column;Importjavax.persistence.Entity;Importjavax.persistence.Id;Importjavax.persistence.Table; @Entity @table (name= "User")//represents the corresponding table name Public classUser {@Id @Column (name= "UID")    Private intID; @Column (Name= "Uname")    PrivateString name; @Column (Name= "UPass")    PrivateString password;  Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString GetPassword () {returnpassword; }     Public voidSetPassword (String password) { This. Password =password; }            }
User.java

Next is the test file:

If we use the following test code

New Configuration (); Conf.configure ("Hibernate.cfg.xml"); // Read connection parameters and mapping description information Sessionfactory factory == = (user) session.get (user.  Class, 1); System.out.println ("After I have sent the statement");            
System.out.println (User.getid () + "," +user.getname () + "," +user.getpassword ());
Session.close ();

You can see the information printed on the console.

If you replace the Get method above with user user = (user) session.load (user). Class, 1);

By comparing these two results, we can see that the load method uses lazy loading. Using the Load method to get the data, when the program is loaded into the Load method, the program does not actually query the statement from the database, only when the result object of the query uses the GetXXX () method, it is queried in the database.

4,org.hibernate.lazyinitialization:could not initialize Proxy-no Session

If lazy loading is used, and the error occurs, it is likely that the session is closed early. After the session is closed, the getxxx () of the resulting object is called, which makes it an error to query the data from the database. In MVC, if you want to use lazy loading (using the Session.load () method or the Query.iterator () method) to fetch data from the database to the page presentation (the GetXXX method of invoking the object on the page), then after the data layer gets the data object, Do not close the session, because when you close the session, the GetXXX () method is called on the page to throw an exception.

To resolve this approach, either do not use lazy loading, or you can close the session after the page calls the GetXXX () method.

If we put the above

Things to note in "Hibernate" Hibernate using lazy loading

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.