`
newleague
  • 浏览: 1499619 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类

Hibernate检索策略学习之--批量加载

阅读更多

所谓批量加载,即把原本要发送的SQL分批统一发送,比如说原本要发送100条SQL,如果设置batch-size=3,则只需要发送100/3+1=34条,可以提高效率

批量加载分为延迟加载和立即加载,先说立即加在

首先建立测试数据库

 

CREATE TABLE certificate (
  id varchar(100) NOT NULL default '',
  description varchar(100) default '',
  PRIMARY KEY  (id)
);

 

 

CREATE TABLE student (
  team_id varchar(100) default '',
  id varchar(100) NOT NULL default '',
  name varchar(20) default '',
  cardId varchar(20) NOT NULL default '',
  age int(11) default '0',
  PRIMARY KEY  (id)
);


CREATE TABLE team (
  id varchar(100) NOT NULL default '',
  teamName varchar(100) default '',
  PRIMARY KEY  (id)
);


INSERT INTO student VALUES
('5','1','spark','200211332',13),
('4','2','jerry','200233332',23),
('3','3','adidas','200231332',33),
('2','4','zhouxingchi','200231132',43),
('1','5','tomclus','200512345',53),
('1','6','tom','200511345',63);

INSERT INTO team VALUES
('5','team5'),
('4','team4'),
('3','team3'),
('2','team2'),
('1','team1');

INSERT INTO certificate VALUES
('1','card1'),
('2','card2'),
('3','card3'),
('4','card4'),
('5','card5'),
('6','card6');

建立POJO对象

package Search.immediately;

public class Certificate ............{
    private String id;
    private String description;
    private Student stu;

    public Student getStu() ............{
        return stu;
    }

    public void setStu(Student stu) ............{
        this.stu = stu;
    }


    public String getDescription() ............{
        return description;
    }

    public void setDescription(String description) ............{
        this.description = description;
    }

    public String getId() ............{
        return id;
    }

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

 

package Search.immediately;

import java.util.HashSet;
import java.util.Set;


public class Team ............{
    private String id;
    private Set students=new HashSet();
    private String teamName;
    private Set tests;
 
    public Set getTests() ............{
        return tests;
    }
 
    public void setTests(Set tests) ............{
        this.tests = tests;
    }

    public String getId() ............{
        return id;
    }

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

    public String getTeamName() ............{
        return teamName;
    }

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

    public Set getStudents() ............{
        return students;
    }

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

 

package Search.immediately;

public class Certificate ............{
    private String id;
    private String description;
    private Student stu;

    public Student getStu() ............{
        return stu;
    }

    public void setStu(Student stu) ............{
        this.stu = stu;
    }


    public String getDescription() ............{
        return description;
    }

    public void setDescription(String description) ............{
        this.description = description;
    }

    public String getId() ............{
        return id;
    }

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

HBM文件

student.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping package="Search.batch.immediately" >

    <class name="Student" table="student" lazy="false">
       <id name="id" column="id" unsaved-value="null">
         <generator class="uuid.hex"></generator>
       </id>

       <property name="cardId" column="cardId"></property>
       <property name="name" column="name"></property>
       <property name="age" column="age"></property>
       <!--为了设置student-certificate的延迟1对1,设置class的lazy="no-proxy"-->
       <one-to-one name="cer"
                   class="Search.batch.immediately.Certificate"
                   constrained="true"
                   lazy="no-proxy"
                   outer-join="false"
                   cascade="all">
       </one-to-one>
     
       <many-to-one name="team"
                    column="team_id"
                    outer-join="false"
                    class="Search.batch.immediately.Team"></many-to-one>
      </class>
</hibernate-mapping>

Certificate.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping package="Search.batch.immediately" >
    <!--为了设置student-certificate的延迟1对1,设置class的lazy="true"-->
    <class name="Certificate" table="certificate" lazy="true">
       <id name="id" column="id">
         <generator class="foreign">
           <param name="property">stu</param>
         </generator>
       </id>


       <property name="description" column="description"></property>
       <one-to-one name="stu"
                   class="Search.batch.immediately.Student"
                   outer-join="false"
                   constrained="true">
       </one-to-one>
      </class>
</hibernate-mapping>

Team.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping package="Search.batch.immediately" >
    <class name="Team" table="team" lazy="false">
       <id name="id" column="id">
         <generator class="uuid.hex"></generator>
       </id>
       <property name="teamName" column="teamName"></property>
        <!--需要批量加载,设置batch-size="2"-->
       <set name="students"
            lazy="false"
            inverse="true"
            outer-join="false"
           >
         <key column="team_id"></key>
         <one-to-many class="Search.batch.immediately.Student"/>
       </set>
      </class>
</hibernate-mapping>

测试代码:

package Search.batch.immediately;

import java.io.File;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test ...{


    public static void main(String[] args) ...{
        Team team=null;
        String filePath=System.getProperty("user.dir")+File.separator+"src/Search/batch/immediately"+File.separator+"hibernate.cfg.xml";
        File file=new File(filePath);
        SessionFactory sessionFactory=new Configuration().configure(file).buildSessionFactory();
        Session session=sessionFactory.openSession();
        Query query=session.createQuery("from Team t");
        List resultList=query.list();


}

运行,结果如下:

Hibernate: select team0_.id as id2_, team0_.teamName as teamName2_ from team team0_


Hibernate: select students0_.team_id as team5_1_, students0_.id as id1_, students0_.id as id1_0_, students0_.cardId as cardId1_0_, students0_.name as name1_0_, students0_.age as age1_0_, students0_.team_id as team5_1_0_ from student students0_ where students0_.team_id=

Hibernate: select students0_.team_id as team5_1_, students0_.id as id1_, students0_.id as id1_0_, students0_.cardId as cardId1_0_, students0_.name as name1_0_, students0_.age as age1_0_, students0_.team_id as team5_1_0_ from student students0_ where students0_.team_id=?

Hibernate: select students0_.team_id as team5_1_, students0_.id as id1_, students0_.id as id1_0_, students0_.cardId as cardId1_0_, students0_.name as name1_0_, students0_.age as age1_0_, students0_.team_id as team5_1_0_ from student students0_ where students0_.team_id=?

Hibernate: select students0_.team_id as team5_1_, students0_.id as id1_, students0_.id as id1_0_, students0_.cardId as cardId1_0_, students0_.name as name1_0_, students0_.age as age1_0_, students0_.team_id as team5_1_0_ from student students0_ where students0_.team_id=?

Hibernate: select students0_.team_id as team5_1_, students0_.id as id1_, students0_.id as id1_0_, students0_.cardId as cardId1_0_, students0_.name as name1_0_, students0_.age as age1_0_, students0_.team_id as team5_1_0_ from student students0_ where students0_.team_id=?

有5条查询student的SQL(本身有6个学生,但有两个学生属于一个team)
可以看到,这是典型的立即加在,取得team对象后,把team所包含的student取出,如果有100个学生,则会执行100个SQL,这是很没有效率的

我们修改Team的hbm文件,为其配置批量加载student的配置(1对多在set标签上配置,多对1在class标签上配置)

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping package="Search.batch.immediately" >
    <class name="Team" table="team" lazy="false">
       <id name="id" column="id">
         <generator class="uuid.hex"></generator>
       </id>
       <property name="teamName" column="teamName"></property>
        <!--需要批量加载,设置batch-size="2"-->
       <set name="students"
            lazy="false"
            inverse="true"
            outer-join="false"
            batch-size="2"
           >
         <key column="team_id"></key>
         <one-to-many class="Search.batch.immediately.Student"/>
       </set>
      </class>
</hibernate-mapping>

再次运行测试程序,结果如下:

Hibernate: select team0_.id as id2_, team0_.teamName as teamName2_ from team team0_

Hibernate: select students0_.team_id as team5_1_, students0_.id as id1_, students0_.id as id1_0_, students0_.cardId as cardId1_0_, students0_.name as name1_0_, students0_.age as age1_0_, students0_.team_id as team5_1_0_ from student students0_ where students0_.team_id in (?, ?)

Hibernate: select students0_.team_id as team5_1_, students0_.id as id1_, students0_.id as id1_0_,
students0_.cardId as cardId1_0_, students0_.name as name1_0_, students0_.age as age1_0_, students0_.team_id as team5_1_0_ from student students0_ where students0_.team_id in (?, ?)

Hibernate: select students0_.team_id as team5_1_, students0_.id as id1_, students0_.id as id1_0_, students0_.cardId as cardId1_0_, students0_.name as name1_0_, students0_.age as age1_0_, students0_.team_id as team5_1_0_ from student students0_ where students0_.team_id=?

可以看到,查询student只用了3条SQL(5/batch-size+1=3),

如果team对student是延迟加载的,会使什么效果呢,会是这样,我们加载team1时候,由于batch-size=2,所以加载team1就同时批量加载了team2,同理,加载team3时候也就加载了team4,最后再加载team5,  而这些数据都已经在hibernate session的缓存中了

修改team.hbm.xml 配置好lazy="true"

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping package="Search.batch.immediately" >
    <class name="Team" table="team" lazy="false">
       <id name="id" column="id">
         <generator class="uuid.hex"></generator>
       </id>
       <property name="teamName" column="teamName"></property>
        <!--需要批量加载,设置batch-size="2"-->
       <set name="students"
            lazy="true"
            inverse="true"
            outer-join="false"
            batch-size="2"
           >
         <key column="team_id"></key>
         <one-to-many class="Search.batch.immediately.Student"/>
       </set>
      </class>
</hibernate-mapping>

运行测试程序,结果如下:

Hibernate: select team0_.id as id2_, team0_.teamName as teamName2_ from team team0_

Hibernate: select students0_.team_id as team5_1_, students0_.id as id1_, students0_.id as id1_0_, students0_.cardId as cardId1_0_, students0_.name as name1_0_, students0_.age as age1_0_, students0_.team_id as team5_1_0_ from student students0_ where students0_.team_id in (?, ?)
team1:2
team2:1

Hibernate: select students0_.team_id as team5_1_, students0_.id as id1_, students0_.id as id1_0_, students0_.cardId as cardId1_0_, students0_.name as name1_0_, students0_.age as age1_0_, students0_.team_id as team5_1_0_ from student students0_ where students0_.team_id in (?, ?)
team3:1
team4:1

Hibernate: select students0_.team_id as team5_1_, students0_.id as id1_, students0_.id as id1_0_, students0_.cardId as cardId1_0_, students0_.name as name1_0_, students0_.age as age1_0_, students0_.team_id as team5_1_0_ from student students0_ where students0_.team_id=?
team5:1

其中可以砍到team2和team4的数据是批量加载来的,已经保存在缓存中,所以读取其students集合对象是,虽然是延迟加载,但不再会去发送SQ查询,而是再缓冲中查询

 

分享到:
评论

相关推荐

    HIBERNATE检索策略

    标题:“HIBERNATE检索策略” 描述:本文深入解析了HIBERNATE的检索策略,为读者提供了一条清晰的学习路径,重点分析了HIBERNATE中的抓取策略及其应用场景,帮助开发者更有效地管理和优化数据加载过程。 在...

    day36-hibernate检索和优化 02-Hibernate检索方式:简单查询及别名查询

    本教程将深入探讨"day36-hibernate检索和优化 02-Hibernate检索方式:简单查询及别名查询"的主题,通过源码分析和实际工具的应用,来提升数据库查询的效率。 首先,我们了解Hibernate的检索方式。在Hibernate中,...

    Hibernate-3.2-API-EN.chm中,英文都有

    4. **检索(Load/Get)**:`Session.load()`基于主键直接加载对象,而`Session.get()`则提供了一种查询方式,如果没有找到匹配的对象,返回`null`。 **五、查询语言(HQL)** Hibernate Query Language (HQL) 是一...

    hibernate面试题2

    1. **Hibernate检索策略**: - **立即检索(Eager Fetching)**:优点在于透明度高,方便导航关联对象,但可能导致过多的SELECT语句和内存浪费。 - **延迟检索(Lazy Fetching)**:应用程序可以根据需要决定何时...

    hibernate-entitymanager-3.3.0.GA

    - **懒加载**:利用Hibernate的懒加载机制,只在需要时加载关联的对象,减少内存占用。 - **缓存策略**:合理使用第一级缓存和第二级缓存,提升数据访问效率。 - **批处理**:批量处理操作可以显著提高性能,如...

    hibernate视频

    - **懒加载**:默认情况下,Hibernate在需要时才加载关联对象的数据。 - **立即加载**:在加载当前对象时立即加载其关联对象的数据。 ### 六、高级特性 #### 6.1 分布式事务管理 - **JTA**:Java Transaction API...

    达内HIBERNATE学习笔记

    根据提供的信息,我们可以总结出以下关于达内HIBERNATE学习笔记的重要知识点: ### 第一章:Hibernate入门 #### 1.1 学习目标 - 理解Hibernate的基本概念。 - 掌握如何使用Hibernate进行开发。 #### 1.2 对象持久...

    hibernate-3.0.5-api

    4. 加载和检索:使用Session的get()或load()方法加载对象,query()方法执行查询。 五、查询语言 1. HQL:Hibernate的查询语言,类似于SQL,但面向对象,支持复杂的查询表达式和函数。 2. Criteria API:提供更面向...

    Hibernate学习

    【Hibernate学习】 Hibernate是一款强大的Java持久化框架,它简化了数据库与Java对象之间的交互,使得开发者无需关注底层的SQL语句,而是通过面向对象的方式来操作数据库。本资料深入浅出地介绍了Hibernate的核心...

    hibernate-orm-4.3.zip

    《Hibernate ORM 4.3 源码解析》 Hibernate ORM 4.3 是一...通过深入学习Hibernate ORM 4.3的源代码,开发者不仅可以提升自己的Java EE开发技能,还能对ORM框架有更全面的理解,为今后的项目开发提供强大的技术支持。

    hibernate入门与概述

    - Hibernate支持多种检索策略,如懒加载、立即加载、批量加载等,优化数据检索性能。 - 通过`fetch`属性和`join`关键字可以控制关联数据的加载时机。 总之,Hibernate通过对象关系映射技术,简化了Java应用与...

    Hibernate框架jia包

    Hibernate框架是中国Java开发领域广泛应用的对象关系映射(ORM)框架,它简化了数据库与Java对象之间的交互。这个“Hibernate框架jia包”包含了你需要在项目中使用Hibernate的所有核心库和依赖,确保你能顺利进行...

    hibernate 入门经典实例

    - 使用`Session`的`createCriteria`或`createQuery`方法批量加载数据,并设置立即加载策略。 #### 实验六:批量延迟加载 **实验目的:** - 掌握批量数据的延迟加载技术。 **实验步骤:** - 在批量查询时配置...

    hibernate框架开发视频资料

    - **懒加载**:默认情况下,Hibernate会延迟加载关联对象,直到真正使用时才从数据库中加载数据,这样可以避免不必要的数据库访问,提高性能。 - **批量处理**:对于大量数据的插入、更新操作,可以使用批量处理方式...

    hibernate_reference

    在给定的文档标题“hibernate_reference”和描述“hibernate_reference 中文Hibernate学习”中,我们可以推断出这份文档的主要目的是为学习Hibernate提供指南和参考资料。 #### 版本信息 文档提到的版本是3.0.4版...

    Hibernate逍遥游记 .pdf

    Hibernate提供了多种性能优化的策略,包括但不限于: - 使用二级缓存来减少数据库访问。 - 使用懒加载来减少一次查询中的数据加载量。 - 通过批量操作和批处理更新来提高处理大量数据的效率。 通过以上知识点的掌握...

    java私塾独家首发最新Hibernate4教程

    ### Hibernate4核心知识点详解 #### 一、Hibernate4简介与...通过上述知识点的学习,可以全面了解Hibernate4的核心功能及其在实际项目中的应用技巧,帮助开发者更好地利用Hibernate4来提高Java应用的开发效率和质量。

    [尚硅谷]_佟刚_Hibernate面试题分析

    - HQL检索:使用Hibernate Query Language进行对象检索。 - QBC检索:基于Query By Criteria的检索方式,无需编写SQL语句。 - 本地SQL检索:直接使用原生SQL语句进行数据检索。 2. Hibernate中Java对象的状态...

    Hibernate开发手册

    - **定义**:Hibernate 是一种用于 Java 应用程序中的对象关系映射(Object-Relational Mapping,简称 ORM)框架,它能够将 Java 类与数据库表建立起对应关系,从而实现对象到关系型数据库的数据存储和检索。...

Global site tag (gtag.js) - Google Analytics