`

Hibernate检索策略

阅读更多
1. Hibernate检索策略

新建项目Hibernate09


hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!--数据库连接设置 -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate4</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <!-- 方言 -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <!-- 控制台显示SQL -->
        <property name="show_sql">true</property>
        <!-- 自动更新表结构 -->
        <property name="hbm2ddl.auto">update</property>
        <!-- Mapper -->
        <mapping resource="com/andrew/model/Student.hbm.xml"/>
        <mapping resource="com/andrew/model/Class.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

HibernateUtil.java

package com.andrew.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();
    private static SessionFactory buildSessionFactory() {
        // 1. 实例化配置文件
        Configuration configuration = new Configuration().configure();
        // 2. 实例化服务登记
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
        // 3. 获取Session工厂
        return configuration.buildSessionFactory(serviceRegistry);
    }
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Class.java

package com.andrew.model;
import java.util.HashSet;
import java.util.Set;
public class Class {
    private long id;
    private String name;
    private Set<Student> students = new HashSet<Student>();
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Set<Student> getStudents() {
        return students;
    }
    public void setStudents(Set<Student> students) {
        this.students = students;
    }
}

Class.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.andrew.model">
    <class name="Class" table="t_class">
        <id name="id" column="classId">
            <generator class="native"></generator>
        </id>
        <property name="name" column="className"></property>
        <set name="students" cascade="delete" inverse="true">
            <key column="classId"></key>
            <one-to-many class="com.andrew.model.Student"/>
        </set>
    </class>
</hibernate-mapping>

Student.java

package com.andrew.model;
public class Student {
    private long id;
    private String name;
    private Class c;
    
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Class getC() {
        return c;
    }
    public void setC(Class c) {
        this.c = c;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + "]";
    }
}

Student.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.andrew.model">
    <class name="Student" table="t_student">
        <id name="id" column="stuId">
            <generator class="native"></generator>
        </id>
        <property name="name" column="stuName"></property>
        <many-to-one name="c" column="classId" class="com.andrew.model.Class" cascade="save-update"></many-to-one>
    </class>
</hibernate-mapping>

StudentTest.java

package com.andrew.service;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.andrew.util.HibernateUtil;
public class StudentTest {
    private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    private Session session;
    @Before
    public void setUp() throws Exception {
        session = sessionFactory.openSession(); // 1. 生成一个session
        session.beginTransaction(); // 2. 开启事务
    }
    @After
    public void tearDown() throws Exception {
        session.getTransaction().commit(); // 3. 提交事务
        session.close(); // 4. 关闭session
    }
}

insert into t_class values(1, '10级1班');
insert into t_class values(2, '10级2班');
insert into t_class values(3, '10级3班');
insert into t_student values(1, '张三', 1);
insert into t_student values(2, '李四', 1);
insert into t_student values(3, '王五', 1);
insert into t_student values(4, '赵六', 2);
insert into t_student values(5, '小七', 2);
insert into t_student values(6, '小八', 2);


1) 检索策略属性Lazy

1.1) Lazy: true (默认)延迟检索;set端一对多

Class.hbm.xml

<set name="students" cascade="delete" inverse="true" lazy="true">
    <key column="classId"></key>
    <one-to-many class="com.andrew.model.Student"/>
</set>

Student.hbm.xml

<many-to-one name="c" column="classId" class="com.andrew.model.Class" cascade="save-update"></many-to-one>

StudentTest.java

@Test
public void testLazy1() {
    Class c = (Class)session.get(Class.class, Long.valueOf(1));
}
@Test
public void testLazy2() {
    Class c = (Class)session.get(Class.class, Long.valueOf(1));
    Set<Student> studentList = (Set<Student>)c.getStudents();
    studentList.iterator();
}

运行结果:
Hibernate: select class0_.classId as classId1_0_0_, class0_.className as classNam2_0_0_ from t_class class0_ where class0_.classId=?
运行结果:
Hibernate: select class0_.classId as classId1_0_0_, class0_.className as classNam2_0_0_ from t_class class0_ where class0_.classId=?
Hibernate: select students0_.classId as classId3_0_0_, students0_.stuId as stuId1_1_0_, students0_.stuId as stuId1_1_1_, students0_.stuName as stuName2_1_1_, students0_.classId as classId3_1_1_ from t_student students0_ where students0_.classId=?


1.2) Lazy: false 立即检索;set端一对多

Class.hbm.xml

<set name="students" cascade="delete" inverse="true" lazy="false">
    <key column="classId"></key>
    <one-to-many class="com.andrew.model.Student"/>
</set>

Student.hbm.xml

<many-to-one name="c" column="classId" class="com.andrew.model.Class" cascade="save-update"></many-to-one>

StudentTest.java

@Test
public void testLazy1() {
    Class c = (Class)session.get(Class.class, Long.valueOf(1));
}
@Test
public void testLazy2() {
    Class c = (Class)session.get(Class.class, Long.valueOf(1));
    Set<Student> studentList = (Set<Student>)c.getStudents();
    studentList.iterator();
}

运行结果:
Hibernate: select class0_.classId as classId1_0_0_, class0_.className as classNam2_0_0_ from t_class class0_ where class0_.classId=?
Hibernate: select students0_.classId as classId3_0_0_, students0_.stuId as stuId1_1_0_, students0_.stuId as stuId1_1_1_, students0_.stuName as stuName2_1_1_, students0_.classId as classId3_1_1_ from t_student students0_ where students0_.classId=?
运行结果:
Hibernate: select class0_.classId as classId1_0_0_, class0_.className as classNam2_0_0_ from t_class class0_ where class0_.classId=?
Hibernate: select students0_.classId as classId3_0_0_, students0_.stuId as stuId1_1_0_, students0_.stuId as stuId1_1_1_, students0_.stuName as stuName2_1_1_, students0_.classId as classId3_1_1_ from t_student students0_ where students0_.classId=?


1.3) Lazy: extra 增强延迟检索;set端一对多

Class.hbm.xml

<set name="students" cascade="delete" inverse="true" lazy="extra">
    <key column="classId"></key>
    <one-to-many class="com.andrew.model.Student"/>
</set>

Student.hbm.xml

<many-to-one name="c" column="classId" class="com.andrew.model.Class" cascade="save-update"></many-to-one>

StudentTest.java

@Test
public void testLazy3() {
    Class c = (Class)session.get(Class.class, Long.valueOf(1));
    Set<Student> studentList = (Set<Student>)c.getStudents();
    System.out.println(studentList.size());
}

运行结果:
Hibernate: select class0_.classId as classId1_0_0_, class0_.className as classNam2_0_0_ from t_class class0_ where class0_.classId=?
Hibernate: select count(stuId) from t_student where classId =?
3


1.4) Lazy: proxy(默认)延迟检索;many-to-one多对一

Class.hbm.xml

<set name="students" cascade="delete" inverse="true">
    <key column="classId"></key>
    <one-to-many class="com.andrew.model.Student"/>
</set>

Student.hbm.xml

<many-to-one name="c" column="classId" class="com.andrew.model.Class" cascade="save-update" lazy="proxy"></many-to-one>

StudentTest.java

@Test
public void testLazy4() {
    Student student = (Student)session.get(Student.class, Long.valueOf(1));
    student.getC().getName();
}

运行结果:
Hibernate: select student0_.stuId as stuId1_1_0_, student0_.stuName as stuName2_1_0_, student0_.classId as classId3_1_0_ from t_student student0_ where student0_.stuId=?
运行时执行
Hibernate: select class0_.classId as classId1_0_0_, class0_.className as classNam2_0_0_ from t_class class0_ where class0_.classId=?


1.5) Lazy: no-proxy 无代理延迟检索;many-to-one多对一(需要编译时字节码增强)

Class.hbm.xml

<set name="students" cascade="delete" inverse="true">
    <key column="classId"></key>
    <one-to-many class="com.andrew.model.Student"/>
</set>

Student.hbm.xml

<many-to-one name="c" column="classId" class="com.andrew.model.Class" cascade="save-update" lazy="no-proxy"></many-to-one>

StudentTest.java

@Test
public void testLazy4() {
    Student student = (Student)session.get(Student.class, Long.valueOf(1));
    student.getC().getName();
}

运行结果:
Hibernate: select student0_.stuId as stuId1_1_0_, student0_.stuName as stuName2_1_0_, student0_.classId as classId3_1_0_ from t_student student0_ where student0_.stuId=?
运行时执行
Hibernate: select class0_.classId as classId1_0_0_, class0_.className as classNam2_0_0_ from t_class class0_ where class0_.classId=?


2) 检索策略属性batch-size

2.1) 批量延迟检索

Class.hbm.xml

<set name="students" cascade="delete" inverse="true" lazy="true" batch-size="3">
    <key column="classId"></key>
    <one-to-many class="com.andrew.model.Student"/>
</set>

Student.hbm.xml

<many-to-one name="c" column="classId" class="com.andrew.model.Class" cascade="save-update" lazy="no-proxy"></many-to-one>

StudentTest.java

@Test
public void testBatch1() {
    List<Class> classList = session.createQuery("from Class").list();
}
@Test
public void testBatch2() {
    List<Class> classList = session.createQuery("from Class").list();
    Iterator it = classList.iterator();
    Class c1 = (Class)it.next();
    Class c2 = (Class)it.next();
    Class c3 = (Class)it.next();
    c1.getStudents().iterator();
    c2.getStudents().iterator();
    c3.getStudents().iterator();
}

运行结果:
Hibernate: select class0_.classId as classId1_0_, class0_.className as classNam2_0_ from t_class class0_
运行结果:
Hibernate: select class0_.classId as classId1_0_, class0_.className as classNam2_0_ from t_class class0_
Hibernate: select students0_.classId as classId3_0_1_, students0_.stuId as stuId1_1_1_, students0_.stuId as stuId1_1_0_, students0_.stuName as stuName2_1_0_, students0_.classId as classId3_1_0_ from t_student students0_ where students0_.classId in (?, ?, ?)


Class.hbm.xml

<set name="students" cascade="delete" inverse="true" lazy="true" batch-size="2">
    <key column="classId"></key>
    <one-to-many class="com.andrew.model.Student"/>
</set>

运行结果:
Hibernate: select class0_.classId as classId1_0_, class0_.className as classNam2_0_ from t_class class0_
运行结果:
Hibernate: select class0_.classId as classId1_0_, class0_.className as classNam2_0_ from t_class class0_
Hibernate: select students0_.classId as classId3_0_1_, students0_.stuId as stuId1_1_1_, students0_.stuId as stuId1_1_0_, students0_.stuName as stuName2_1_0_, students0_.classId as classId3_1_0_ from t_student students0_ where students0_.classId in (?, ?)
Hibernate: select students0_.classId as classId3_0_1_, students0_.stuId as stuId1_1_1_, students0_.stuId as stuId1_1_0_, students0_.stuName as stuName2_1_0_, students0_.classId as classId3_1_0_ from t_student students0_ where students0_.classId=?


2.2) 批量立即检索

Class.hbm.xml

<set name="students" cascade="delete" inverse="true" lazy="false" batch-size="3">
    <key column="classId"></key>
    <one-to-many class="com.andrew.model.Student"/>
</set>

Student.hbm.xml

<many-to-one name="c" column="classId" class="com.andrew.model.Class" cascade="save-update" lazy="no-proxy"></many-to-one>

StudentTest.java

@Test
public void testBatch1() {
    List<Class> classList = session.createQuery("from Class").list();
}

运行结果:
Hibernate: select class0_.classId as classId1_0_, class0_.className as classNam2_0_ from t_class class0_
Hibernate: select students0_.classId as classId3_0_1_, students0_.stuId as stuId1_1_1_, students0_.stuId as stuId1_1_0_, students0_.stuName as stuName2_1_0_, students0_.classId as classId3_1_0_ from t_student students0_ where students0_.classId in (?, ?, ?)


Class.hbm.xml

<set name="students" cascade="delete" inverse="true" lazy="false" batch-size="2">
    <key column="classId"></key>
    <one-to-many class="com.andrew.model.Student"/>
</set>

运行结果:
Hibernate: select class0_.classId as classId1_0_, class0_.className as classNam2_0_ from t_class class0_
Hibernate: select students0_.classId as classId3_0_1_, students0_.stuId as stuId1_1_1_, students0_.stuId as stuId1_1_0_, students0_.stuName as stuName2_1_0_, students0_.classId as classId3_1_0_ from t_student students0_ where students0_.classId in (?, ?)
Hibernate: select students0_.classId as classId3_0_1_, students0_.stuId as stuId1_1_1_, students0_.stuId as stuId1_1_0_, students0_.stuName as stuName2_1_0_, students0_.classId as classId3_1_0_ from t_student students0_ where students0_.classId=?


3) 检索策略属性Fetch

3.1) Fetch:select(默认)查询方式

Class.hbm.xml

<set name="students" cascade="delete" inverse="true" lazy="false" batch-size="2" fetch="select">
    <key column="classId"></key>
    <one-to-many class="com.andrew.model.Student"/>
</set>

Student.hbm.xml

<many-to-one name="c" column="classId" class="com.andrew.model.Class" cascade="save-update" lazy="no-proxy"></many-to-one>

StudentTest.java

@Test
public void testFetch1() {
    List<Class> classList = session.createQuery("from Class").list();
    Iterator it = classList.iterator();
    Class c1 = (Class)it.next();
    Class c2 = (Class)it.next();
    Class c3 = (Class)it.next();
    c1.getStudents().iterator();
    c2.getStudents().iterator();
    c3.getStudents().iterator();
}

运行结果:
Hibernate: select class0_.classId as classId1_0_, class0_.className as classNam2_0_ from t_class class0_
Hibernate: select students0_.classId as classId3_0_1_, students0_.stuId as stuId1_1_1_, students0_.stuId as stuId1_1_0_, students0_.stuName as stuName2_1_0_, students0_.classId as classId3_1_0_ from t_student students0_ where students0_.classId in (?, ?)
Hibernate: select students0_.classId as classId3_0_1_, students0_.stuId as stuId1_1_1_, students0_.stuId as stuId1_1_0_, students0_.stuName as stuName2_1_0_, students0_.classId as classId3_1_0_ from t_student students0_ where students0_.classId=?


3.2) Fetch:subselect子查询方式

Class.hbm.xml

<set name="students" cascade="delete" inverse="true" lazy="false" batch-size="2" fetch="subselect">
    <key column="classId"></key>
    <one-to-many class="com.andrew.model.Student"/>
</set>

Student.hbm.xml

<many-to-one name="c" column="classId" class="com.andrew.model.Class" cascade="save-update" lazy="no-proxy"></many-to-one>

StudentTest.java

@Test
public void testFetch1() {
    List<Class> classList = session.createQuery("from Class").list();
    Iterator it = classList.iterator();
    Class c1 = (Class)it.next();
    Class c2 = (Class)it.next();
    Class c3 = (Class)it.next();
    c1.getStudents().iterator();
    c2.getStudents().iterator();
    c3.getStudents().iterator();
}

运行结果:
Hibernate: select class0_.classId as classId1_0_, class0_.className as classNam2_0_ from t_class class0_
Hibernate: select students0_.classId as classId3_0_1_, students0_.stuId as stuId1_1_1_, students0_.stuId as stuId1_1_0_, students0_.stuName as stuName2_1_0_, students0_.classId as classId3_1_0_ from t_student students0_ where students0_.classId in (select class0_.classId from t_class class0_)


3.3) Fetch:join迫切左外连接查询方式

Class.hbm.xml

<set name="students" cascade="delete" inverse="true" lazy="false" batch-size="2" fetch="join">
    <key column="classId"></key>
    <one-to-many class="com.andrew.model.Student"/>
</set>

Student.hbm.xml

<many-to-one name="c" column="classId" class="com.andrew.model.Class" cascade="save-update" lazy="no-proxy"></many-to-one>

StudentTest.java

@Test
public void testFetch2() {
    Class c = (Class)session.get(Class.class, Long.valueOf(1));
}

运行结果:
Hibernate: select class0_.classId as classId1_0_0_, class0_.className as classNam2_0_0_, students1_.classId as classId3_0_1_, students1_.stuId as stuId1_1_1_, students1_.stuId as stuId1_1_2_, students1_.stuName as stuName2_1_2_, students1_.classId as classId3_1_2_ from t_class class0_ left outer join t_student students1_ on class0_.classId=students1_.classId where class0_.classId=?
分享到:
评论

相关推荐

    HIBERNATE检索策略

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

    Hibernate的检索策略

    ### Hibernate的检索策略详解 #### 一、概述 在Java持久化框架Hibernate中,检索策略是一种重要的机制,它主要用于控制对象何时以及如何加载到应用程序内存中。合理的检索策略不仅可以提高应用性能,还能简化代码...

    hibernate的检索

    【Hibernate检索策略】 Hibernate提供三种主要的检索策略:立即检索、延迟检索和迫切左外连接检索。 1. **立即检索**:这种策略将立即加载关联的对象,无论对象是持久化状态还是游离状态。优点是应用程序可以方便...

    hibernate5--4.检索方式及策略

    一、Hibernate检索方式 1. **HQL(Hibernate Query Language)**: HQL是Hibernate提供的面向对象的查询语言,类似于SQL,但它是基于类和对象的。你可以通过HQL来查询、更新和删除对象,而无需关心底层的SQL语法。...

    hibernate面试题2

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

    SSH笔记-检索策略(lazy、fetch、batch-size)

    SSH笔记主要涵盖了Spring、Struts和...SSHnote_Retrieval文件可能包含的是关于SSH框架特别是Hibernate检索策略的详细示例代码、配置文件或教程,通过阅读和实践这些内容,可以帮助开发者深入理解和应用上述知识。

    Hibernate3.2整套源码

    3. **Hibernate检索策略**:包括“立即加载”和“延迟加载”,可以根据需求选择何时加载关联的对象。 4. **类型系统增强**:增加了对枚举类型的支持,以及更加灵活的类型转换机制。 5. **JPA支持**:Hibernate 3.2...

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

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

    Hibernate开发指南

    - 高级特性: Criteria API、Hibernate检索策略、事件监听器、拦截器 - 性能调优和最佳实践 - 实战案例分析 通过阅读这些资料,你将能够掌握Hibernate的基本操作和进阶技巧,从而高效地进行Java ORM开发。在实践...

    基于Spring的Hibernate Search全文检索功能示例

    3. **Hibernate Search**:作为Hibernate的一个扩展,Hibernate Search提供了基于Lucene的全文检索功能,使得在数据库中的数据可以被快速、精确地搜索。 **二、集成Hibernate Search** 1. **配置依赖**:首先,你...

    Hibernate学习总结

    学习成长路,Hibernate总结: 1.Hibernate入门优缺点、 2.Hibernate的操作CRUD、 3.主键生成机制、 4.持久化对象的状态、 ...8.Hibernate检索策略(fetch抓取策略)、 9.二级缓存、 10.Hbernate的检索方式(HQL语句)

    Hibernate检索方式

    ### Hibernate检索方式详解 #### 一、概述 Hibernate是一个强大的对象关系映射(ORM)框架,它可以将Java对象与数据库表进行映射,使得开发者能够更方便地进行数据的持久化操作。在Hibernate中,提供了多种检索...

    hibernate基础 注解开发 检索

    ### Hibernate基础:注解开发与检索 #### 一、Hibernate注解开发概述 **Hibernate**是一种流行的Java持久层框架,提供了对象关系映射(ORM)的功能,使得Java开发者能够更高效地进行数据库操作。注解作为Java SE 5...

    hibernate3数据检索、抓取策略 、 注解的使用

    hibernate3数据检索、抓取策略 、 注解的使用

    J2EE Hibernate-6.ppt

    《J2EE Hibernate-6.ppt》探讨了Hibernate在J2EE环境中的检索策略,主要涉及立即检索策略、延迟检索策略以及迫切左外连接检索策略。 1. **立即检索策略**: 立即检索策略是Hibernate默认的检索方式。在处理一对多...

    JAVA软件工程课程体系

    Hibernate3对象关系映射、操纵持久化对象、Hibernate相关映射、Hibernate检索策略、Hibernate检索方式、Hibernate高级配置、Java语言的反射机制、iBATIS原理及使用;Spring2概述、bean和BeanFactory等。 通过上述...

    Hibernate实战笔记

    - **Hibernate中的n+1查询问题**:当使用默认的立即检索策略时,Hibernate会在检索一个对象的同时检索其关联的所有对象。例如,在一个`Customer`与多个`Order`的关联关系中,如果数据库中有`n`个客户,则Hibernate将...

Global site tag (gtag.js) - Google Analytics