Hibernate lazy loading FOR Connection

Hibernate Collection property of lazy loading policy  :

 In the collection properties, you can configure the lazy loading policy  , A value of  :true/false/extra

true: The default value, which means that only the collection gets inside the element object  , Before issuing the query statement, loading its
      The collection of data elements
false: Cancel the lazy load characteristics, i.e. while loading the object  , The second query statement to load data to the associated collection
extra: A clever lazy loading policy, which is called the collection  size/contains When methods such as  ,hibernate
       And not to load the entire collection of data, and is issued a clever  SQL Statements, in order to get the required values  , Only in
       The real need to use the collection element object data when going to issue a query statement to load all the data of the object

The following to-many map-based way. On the side of the relevant settings set to lazy to test.

As follows:

package com.bjsxt.hibernate;

import java.util.Set;

public class Classes {

        private int id;

        private String name;

        private Set students;

        public int getId() {
                return id;
        }

        public void setId(int id) {
                this.id = id;
        }

        public String getName() {
                return name;
        }

        public void setName(String name) {
                this.name = name;
        }

        public Set getStudents() {
                return students;
        }

        public void setStudents(Set students) {
                this.students = students;
        }

}
package com.bjsxt.hibernate;

public class Student {

        private int id;

        private String name;

        public int getId() {
                return id;
        }

        public void setId(int id) {
                this.id = id;
        }

        public String getName() {
                return name;
        }

        public void setName(String name) {
                this.name = name;
        }
}

Classes.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
        <class name="com.bjsxt.hibernate.Classes" table="t_classes">
                <id name="id">
                        <generator/>
                </id>
                <property name="name"/>
                <!--
                        <set name="students" cascade="all" order-by="id">
                 -->
                 <set name="students" lazy="extra">
                        <key column="classid"/>
                        <one-to-many/>
                </set>
        </class>
</hibernate-mapping>

Student.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
        <class name="com.bjsxt.hibernate.Student" table="t_student">
                <id name="id">
                        <generator/>
                </id>
                <property name="name"/>
        </class>
</hibernate-mapping>

Configure-to-many mapping above.

As the next set of three property values in LAZY true / false / extra can set the following, we were tested.

1, true: the default value, it means that only the call to get this set of elements inside the object, when it issued the query, load the collection of data elements

package com.bjsxt.hibernate;

import java.util.Iterator;
import java.util.Set;

import org.hibernate.Session;

import junit.framework.TestCase;

/**
 *  Keep the default value for the lazy
 * @author Administrator
 *
 */
public class CollectionLazyTest1 extends TestCase {

        public void testLoadClasses1() {
                Session session = null;
                try {
                        session = HibernateUtils.getSession();

                        // Never send query  sql
                        Classes classes = (Classes)session.load(Classes.class, 1);

                        // Sends a query to load data into sql,  classes
                        System.out.println(" Class  :[" + classes.getName() + "]   Have students  :");

                        // Never send query  sql
                        Set students = classes.getStudents();

                        // Sends a query to load data into sql,  Students
                        for (Iterator iter = students.iterator(); iter.hasNext();) {
                                Student student = (Student)iter.next();
                                System.out.println(student.getName());
                        }
                }catch(Exception e) {
                        e.printStackTrace();
                }finally {
                        HibernateUtils.closeSession(session);
                }
        }

        public void testLoadClasses2() {
                Session session = null;
                try {
                        session = HibernateUtils.getSession();

                        // Never send query  sql
                        Classes classes = (Classes)session.load(Classes.class, 1);

                        // Sends a query to load data into sql,  classes
                        System.out.println(" Class  :[" + classes.getName() + "]   The total number of students  :");

                        // Never send query  sql
                        Set students = classes.getStudents();

                        // Will issue a query SQL, load all of the data to the  Students
                        System.out.println(students.size());

                }catch(Exception e) {
                        e.printStackTrace();
                }finally {
                        HibernateUtils.closeSession(session);
                }
        }

}

The implementation of the above results of two methods:

testLoadClasses1 Results:

Hibernate: select classes0_.id as id0_0_, classes0_.name as name0_0_ from t_classes classes0_ where classes0_.id=?
 Class  :[ Class  ]   Have students  :
Hibernate: select students0_.classid as classid0_1_, students0_.id as id1_, students0_.id as id1_0_, students0_.name as name1_0_ from t_student students0_ where students0_.classid=?
 Students  _6
 Students  _9
 Students  _2
 Students  _0
 Students  _4
 Students  _1
 Students  _8
 Students  _7
 Students  _5
 Students  _3

testLoadClasses2 Results:

Hibernate: select classes0_.id as id0_0_, classes0_.name as name0_0_ from t_classes classes0_ where classes0_.id=?
 Class  :[ Class  ]   The total number of students  :
Hibernate: select students0_.classid as classid0_1_, students0_.id as id1_, students0_.id as id1_0_, students0_.name as name1_0_ from t_student students0_ where students0_.classid=?
10

2, false: Cancel lazy loading features, that is, the object is loaded, while the second query on the issue of load its associated data collection

package com.bjsxt.hibernate;

import java.util.Iterator;
import java.util.Set;

import org.hibernate.Session;

import junit.framework.TestCase;

/**
 *  Sets the collection of  lazy=false
 * @author Administrator
 *
 */
public class CollectionLazyTest2 extends TestCase {

        public void testLoadClasses1() {
                Session session = null;
                try {
                        session = HibernateUtils.getSession();

                        // Never send query  sql
                        Classes classes = (Classes)session.load(Classes.class, 1);

                        // Will issue two query SQL, loading data to the  classes And Students in
                        System.out.println(" Class  :[" + classes.getName() + "]   Have students  :");

                        // Never send query  sql
                        Set students = classes.getStudents();

                        // Never send query  sql
                        for (Iterator iter = students.iterator(); iter.hasNext();) {
                                Student student = (Student)iter.next();
                                System.out.println(student.getName());
                        }
                }catch(Exception e) {
                        e.printStackTrace();
                }finally {
                        HibernateUtils.closeSession(session);
                }
        }

        public void testLoadClasses2() {
                Session session = null;
                try {
                        session = HibernateUtils.getSession();

                        // Never send query  sql
                        Classes classes = (Classes)session.load(Classes.class, 1);

                        // Will issue two query SQL, loading data to the  classes And Students in
                        System.out.println(" Class  :[" + classes.getName() + "]   The total number of students  :");

                        // Never send query  sql
                        Set students = classes.getStudents();

                        // Never send query  sql
                        System.out.println(students.size());

                }catch(Exception e) {
                        e.printStackTrace();
                }finally {
                        HibernateUtils.closeSession(session);
                }
        }

}

When you call here in testLoadClasses1 method classes.getName () when the note, at this time before the issue of two SQL, as follows:

Hibernate: select classes0_.id as id0_0_, classes0_.name as name0_0_ from t_classes classes0_ where classes0_.id=?
Hibernate: select students0_.classid as classid0_1_, students0_.id as id1_, students0_.id as id1_0_, students0_.name as name1_0_ from t_student students0_ where students0_.classid=?
 Class  :[ Class  ]   Have students  :
 Students  _3
 Students  _9
 Students  _4
 Students  _6
 Students  _5
 Students  _1
 Students  _8
 Students  _0
 Students  _2
 Students  _7

The testLoadClasses2 results are as follows: Note that both SQL is issued when the call classes.getName, followed by print students.size not reissued SQL. This also shows that: the object is loaded, while the second query on the issue of load its associated data collection

Hibernate: select classes0_.id as id0_0_, classes0_.name as name0_0_ from t_classes classes0_ where classes0_.id=?
Hibernate: select students0_.classid as classid0_1_, students0_.id as id1_, students0_.id as id1_0_, students0_.name as name1_0_ from t_student students0_ where students0_.classid=?
 Class  :[ Class  ]   The total number of students  :
10

3, extra: a more clever lazy loading strategy that calls the collection of size / contains methods such as time, hibernate
And not going to load the entire collection of data, but issues a smart of the SQL statements in order to obtain the values you only need to use these collections Real element object data while before trying to send Chaxunyuju load all objects data

package com.bjsxt.hibernate;

import java.util.Iterator;
import java.util.Set;

import org.hibernate.Session;

import junit.framework.TestCase;

/**
 *  Sets the collection of  lazy=extra
 * @author Administrator
 *
 */
public class CollectionLazyTest3 extends TestCase {

        public void testLoadClasses1() {
                Session session = null;
                try {
                        session = HibernateUtils.getSession();

                        // Never send query  sql
                        Classes classes = (Classes)session.load(Classes.class, 1);

                        // Sends a query to load data into sql,  classes
                        System.out.println(" Class  :[" + classes.getName() + "]   Have students  :");

                        // Never send query  sql
                        Set students = classes.getStudents();

                        // Sends a query to load data into sql,  students
                        for (Iterator iter = students.iterator(); iter.hasNext();) {
                                Student student = (Student)iter.next();
                                System.out.println(student.getName());
                        }
                }catch(Exception e) {
                        e.printStackTrace();
                }finally {
                        HibernateUtils.closeSession(session);
                }
        }

        public void testLoadClasses2() {
                Session session = null;
                try {
                        session = HibernateUtils.getSession();

                        // Never send query  sql
                        Classes classes = (Classes)session.load(Classes.class, 1);

                        // Sends a query to load data into sql,  classes
                        System.out.println(" Class  :[" + classes.getName() + "]   The total number of students  :");

                        // Never send query  sql
                        Set students = classes.getStudents();

                        // Will issue a more intelligent query SQL, such as  :
                        //select count(id) from t_student where classid =?
                        System.out.println(students.size());

                }catch(Exception e) {
                        e.printStackTrace();
                }finally {
                        HibernateUtils.closeSession(session);
                }
        }

        public void testLoadClasses3() {
                Session session = null;
                try {
                        session = HibernateUtils.getSession();

                        // Never send query  sql
                        Classes classes = (Classes)session.load(Classes.class, 1);

                        // Sends a query to load data into sql,  classes
                        System.out.println(" Class  :[" + classes.getName() + "]   The total number of students  :");

                        // Never send query  sql
                        Set students = classes.getStudents();

                        // Iteration will issue  SQL
                        for (Iterator iter = students.iterator(); iter.hasNext();) {
                                Student student = (Student)iter.next();
                                System.out.println(student.getName());
                        }

                        // Because the earlier iterations out all of the data, so the following does not issue  sql, And testLoadClasses2 of different printing is the total number of iterations before  .
                        System.out.println(students.size());

                }catch(Exception e) {
                        e.printStackTrace();
                }finally {
                        HibernateUtils.closeSession(session);
                }
        }

}

testLoadClasses1 Results:

Hibernate: select classes0_.id as id0_0_, classes0_.name as name0_0_ from t_classes classes0_ where classes0_.id=?
 Class  :[ Class  ]   Have students  :
Hibernate: select students0_.classid as classid0_1_, students0_.id as id1_, students0_.id as id1_0_, students0_.name as name1_0_ from t_student students0_ where students0_.classid=?
 Students  _2
 Students  _8
 Students  _3
 Students  _5
 Students  _4
 Students  _9
 Students  _0
 Students  _7
 Students  _1
 Students  _6

testLoadClasses2 Results:

Hibernate: select classes0_.id as id0_0_, classes0_.name as name0_0_ from t_classes classes0_ where classes0_.id=?
 Class  :[ Class  ]   The total number of students  :
Hibernate: select count(id) from t_student where classid =?
10

Can see that when LAZY = "extra" time would be more intelligent, that students.size () when the calls select count (id) from t_student where classid =?
Total demand.

Comparison of three kinds of value to the difference and connection between, obviously the third method is more optimized

分类:Java 时间:2010-05-10 人气:231
分享到:
blog comments powered by Disqus

相关文章

  • Only using ibatis, the multiple data sources is simply a nightmare, for each data source will need more than an sql-map-config configuration file. 2010-09-14

    Only using ibatis, the multiple data sources is simply a nightmare, for each data source will need more than an sql-map-config configuration file. By spring of AbstractRoutingDataSource can simply solve this problem. AbstractRoutingDataSource implements j

  • JAVA date string Hu Zhuan 2008-10-30

    package test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Test ( public static void main (String [] args) ( SimpleDateFormat dateTimeFormat = new SimpleDateFormat ( "yyyy-MM-dd HH: mm: ...

  • String.Pattern.Matcher--java Regular 2010-11-07

    1, if you want to object as a regular expression to repeated use, you can use the static method Pattern compile () to compile. compile () method returns a Pattern instance. This instance represents a regular expression, can be reused after the instan

  • Dynamic programming largest public String 2010-11-16

    Dynamic programming ----- seeking maximum public string two strings package zju; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class SameString { public static void main(String[] args){ String s1=

  • organize a common java class (string handling class) 2011-01-11

    Keywords: java string commonly used class of first order today, some of his usual string under common categories: Java code 1.import java.io. *; 2.import java.text.DecimalFormat; 3.import org.apache.oro.text.regex.PatternCompiler; 4.import org.apache

  • Java keywords (string) Filter 2011-04-25

    import java.util.HashMap; / ** * MaxLength-longest length of the string to filter * filterStrs <string,string> - need to filter the set of strings, key for the need to filter a string, value string for the filter into, such as "*" * @ Auth

  • Bash string manipulation (control and Java) - 4 string output 2011-09-08

    Bash string manipulation (control and Java) - 4 string output In Java Output to the standard output device (console, screen) System.out.println (s); Output to the standard error device (the console screen) System.err.println (s); Output to a file Pri

  • Java的string类为什么是不可变的 2014-04-20

    这篇文章主要介绍了Java的string类为什么是不可变的,总结了三个答案,需要的朋友可以参考下 答案一: 最流行的Java面试题之一就是:什么是不可变对象(immutable object),不可变对象有什么好处,在什么情况下应该用,或者更具体一些,Java的String类为什么要设成immutable类型? 不可变对象,顾名思义就是创建后不可以改变的对象,典型的例子就是Java中的String类。 String s = "ABC"; s.toLowerCase(); 如上s.toLowerC

  • Java使用String类格式化当前日期实现代码 2014-05-11

    这篇文章主要介绍了Java使用String类格式化当前日期实现代码,需要的朋友可以参考下 在输出日期信息时,经常需要输出不同格式的日期格式,本实例中介绍了String字符串类中的日期格式化方法,实例使用不同的方式输出String类的日期格式参数值,组合这些值可以实现特殊格式的日期字符串。 思路如下:比如要输出月份的英文简称,通过String类的format()方法,第一个参数指定语言环境为Locale.US,默认为数字,第二个参数即为%tb表示月份简称,第三个参数则为Date()类对象。 代码如

  • java中String与StringBuilder的区别 2015-04-11

    本篇文章介绍了,java中String与StringBuilder的区别。需要的朋友参考下 相信大家对 String 和 StringBuffer 的区别也已经很了解了,但是估计还是会有很多同志对这两个类的工作原理有些不清楚的地方,今天我在这里重新把这个概念给大家复习一下,顺便牵出 J2SE 5.0 里面带来的一个新的字符操作的类—— StringBuilder (先别忙着扔我砖头,我还算清醒,我这里说的不是 C #, Java 也有 StringBuilder 类)。那么这个 StringBu

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.345 (s). 12 q(s)