Hibernate检索策略学习之--延迟加载

本文通过实例介绍如何在Hibernate中配置延迟加载,包括一对多、多对一及一对一的关联关系,展示了如何通过XML映射文件及代码实现延迟加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

所谓延迟加载,是在读取查询对象时,不立即取回其所关联的对象,只返回其对象的一个代理,并没有实际数据,当需要用到关联对象的属性时,这是再发送SQL进行数据库查询,减少了不必要的数据库资源我们有三个实体对象Student,Team,Cerificate

其中Student和Team是1对1的关系,采用主键关联的方式(Student的id和Certificate的id保持一致) 
        Team和Student是一对多的关系(反之为1对多)

在Mysql中运行以下脚本,建立数据库

 



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





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






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



INSERT INTO certificate VALUES ('1','110108');
INSERT INTO certificate VALUES ('2','110109');

INSERT INTO student VALUES ('1','1','tomclus','2006m',33);
INSERT INTO student VALUES ('2','2','tom','2007m',22);
INSERT INTO team VALUES ('1','team1');

 

建立对应的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;
    }

}

本文中,Student和Certificate为还为立即加在,student和team双向1对多,多对1采用延迟加载

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.lazy" >
    
<!-- 设置非延迟加载,由于many-to-one不能设置lazy属性,所以我们在class上
          设置,但one-to-one的cer属性不需要延迟,怎么办呢?我们可以在one-to-one上
          再设置一下lazy="true",这样one-to-one就会使用自己的lazy设置了
-->
    
<class name="Student" table="student" lazy="true">
       
<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>
       
<!-- 为测试立即加载,关闭外连接 -->
       
<one-to-one name="cer" 
                   class
="Search.lazy.Certificate"
                   constrained
="true" 
                   outer-join
="false" 
                   cascade
="all">
       
</one-to-one>
       
<!-- 关闭外连接,并设置lazy="true",表示读取student对象后,并不立即把其所属的team信息取回 
              注意这里并不是设置lazy="true"而是设置lazy="no-proxy"(针对hibernate3),而且还必须在
              其关联的Team的class标签中设置lazy="true"方能实现student对team的延迟加载,
              这个知识点也可以参考http://blog.youkuaiyun.com/daryl715/archive/2007/11/28/1905989.aspx
       
-->
       
<many-to-one name="team" 
                    column
="team_id"
                    outer-join
="false" 
                    lazy
="no-proxy"
                    class
="Search.lazy.Team"></many-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.lazy" >
    
<class name="Team" table="team" lazy="true">
       
<id name="id" column="id">
         
<generator class="uuid.hex"></generator>
       
</id>
       
<property name="teamName" column="teamName"></property>
       
<!-- 关闭外连接,并设置lazy="true",表示读取team对象后,并不立即把其所有的student信息取回 -->
       
<set name="students" lazy="true" inverse="true" outer-join="false">
         
<key column="team_id"></key>
         
<one-to-many class="Search.lazy.Student"/>
       
</set>
      
</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.lazy" > 
    
<class name="Certificate" table="certificate" lazy="false">
       
<!-- 共享主键关联,在子方配置constrained=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.lazy.Student"
                   outer-join
="false" 
                   constrained
="true">
       
</one-to-one>
      
</class>
</hibernate-mapping>

hibernate.cfg.xml

 

<?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.                   -->
<hibernate-configuration>

<session-factory>
    
<property name="connection.username">root</property>
    
<property name="connection.url">
        jdbc:mysql://localhost:3306/hibernateconformity?characterEncoding=gb2312
&amp;useUnicode=true
    
</property>
    
<property name="dialect">
        org.hibernate.dialect.MySQLDialect
    
</property>
    
<property name="myeclipse.connection.profile">mysql</property>
    
<property name="connection.password">1234</property>
    
<property name="connection.driver_class">
        com.mysql.jdbc.Driver
    
</property>
    
<property name="hibernate.dialect">
        org.hibernate.dialect.MySQLDialect
    
</property>
    
<property name="hibernate.show_sql">true</property>
    
<property name="current_session_context_class">thread</property>
    
<mapping resource="Search/lazy/Certificate.hbm.xml" />
    
<mapping resource="Search/lazy/Student.hbm.xml" />
    
<mapping resource="Search/lazy/Team.hbm.xml" />

</session-factory>

</hibernate-configuration>

 

测试代码:

 

package Search.lazy;

import java.io.File;
import java.io.FileInputStream;

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

public class Test {


    
public static void main(String[] args) {
        String filePath
=System.getProperty("user.dir")+File.separator+"src/Search/lazy"+File.separator+"hibernate.cfg.xml";
        File file
=new File(filePath);
        SessionFactory sessionFactory
=new Configuration().configure(file).buildSessionFactory();
        Session session
=sessionFactory.openSession();
        Student stu
=(Student)session.get(Student.class"1");
        System.out.println(stu.getName());
        System.out.println(
"-------------------------");
        System.out.println(stu.getTeam().getTeamName());
        System.out.println(
"-------------------------");
        System.out.println(stu.getTeam().getStudents().size());

    }


}

 

运行结果:

Hibernate: select student0_.id as id1_0_, student0_.cardId as cardId1_0_, student0_.name as name1_0_, student0_.age as age1_0_, student0_.team_id as team5_1_0_ from student student0_ where student0_.id=?
这条语句是因为我们调用了get方式,取id为1的student对象而产生的
Hibernate: select certificat0_.id as id0_0_, certificat0_.description as descript2_0_0_ from certificate certificat0_ where certificat0_.id=?
由于是立即加载,hibernate会自动根据取回的student对象来取得和他对应的Certificate
tomclus
-------------------------
打印学生的名字,可以砍到,这里只执行2条sql
Hibernate: select team0_.id as id2_0_, team0_.teamName as teamName2_0_ from team team0_ where team0_.id=?
当运行System.out.println(stu.getTeam().getTeamName());取student关联的team的时候,这时候才执行sql取team对象,但只是取team对象而已,其关联的student集合并不取回
team1
-------------------------
打印班级的名字
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 certificat0_.id as id0_0_, certificat0_.description as descript2_0_0_ from certificate certificat0_ where certificat0_.id=?
当运行System.out.println(stu.getTeam().getStudents().size());时,发送sql指令,取回team关联的student集合,并根据student和certificate之间的立即加载策略,取回对应的certificate,由于hibernate session的缓存,这里不用再取一边id为1的的student

2

 

特别注意:

如果在System.out.println(stu.getTeam().getTeamName());之前关闭了session,这是运行
System.out.println(stu.getTeam().getTeamName());会出现could not initialize proxy-thw owning Session was close的异常错误,这是因为关闭session对象后,取回的student对象已经从持久太转变成游离态,这时候,如果再进行读取,当然会提示没有session,如果我们这时候重新建立一个session2,则需要把student对象和新session绑定,重新转变成持久抬,方法如下:


session2.update(stu.getTeam());
session2.initialize(stu.getTeam());
session2.initialize(stu.getTeam().getStudents());这一句非常重要,因为initialize方法只处理代理对象和集合,对其再嵌套的对象不起作用,所以,为了能读出team中的student对象,我们需要两次执行initialize()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值