Hibernate检索策略学习之--预先抓取

本文介绍Hibernate框架中的预先加载技术,通过示例展示了如何在一对多和一对一的关系中使用外连接来初始化关联对象。具体实现包括数据库建表、实体类定义、映射文件配置及测试代码。

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

所谓预先加载,是指hibernate通过select语句使用outer join(一般为左外连接left outer join)来获取对象的关联实例或者关联集合(集合被初始化了,这是重点,和延迟加载不同)

我们有三个实体对象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;
    }

}

 

<!--推荐1对多,多对多使用延迟加载,而多1对1,多对1采用预先抓取-->

设置student对team及certificate进行预先抓取

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.fetch" >
   
    
<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>
       
<!--推荐1对多,多对多使用延迟加载,而多1对1,多对1采用预先抓取-->
       
<one-to-one name="cer" 
                   class
="Search.fetch.Certificate"
                   constrained
="true" 
                   outer-join
="true" 
                   cascade
="all">
       
</one-to-one>
      
      
<!--推荐1对多,多对多使用延迟加载,而多1对1,多对1采用预先抓取-->
       
<many-to-one name="team" 
                    column
="team_id"
                    outer-join
="true" 
                    class
="Search.fetch.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.fetch" >
    
<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.fetch.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.fetch" > 
    
<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>
       
<!--推荐1对多,多对多使用延迟加载,而多1对1,多对1采用预先抓取-->
       
<one-to-one name="stu" 
                   class
="Search.fetch.Student"
                   outer-join
="true" 
                   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/fetch/Certificate.hbm.xml" />
    
<mapping resource="Search/fetch/Student.hbm.xml" />
    
<mapping resource="Search/fetch/Team.hbm.xml" />

</session-factory>

</hibernate-configuration>

 

测试代码:

 

package Search.fetch;

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/fetch"+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_3_, student0_.cardId as cardId1_3_, student0_.name as name1_3_, student0_.age as age1_3_, student0_.team_id as team5_1_3_, certificat1_.id as id0_0_, certificat1_.description as descript2_0_0_, student2_.id as id1_1_, student2_.cardId as cardId1_1_, student2_.name as name1_1_, student2_.age as age1_1_, student2_.team_id as team5_1_1_, team3_.id as id2_2_, team3_.teamName as teamName2_2_ from student student0_ inner join certificate certificat1_ on student0_.id=certificat1_.id left outer join student student2_ on certificat1_.id=student2_.id left outer join team team3_ on student0_.team_id=team3_.id where student0_.id=?
使用外连接读取student对象,以及和他关联的team对象,certificate对象
tomclus
-------------------------
team1
-------------------------
Hibernate: select students0_.team_id as team5_3_, students0_.id as id3_, students0_.id as id1_2_, students0_.cardId as cardId1_2_, students0_.name as name1_2_, students0_.age as age1_2_, students0_.team_id as team5_1_2_, certificat1_.id as id0_0_, certificat1_.description as descript2_0_0_, student2_.id as id1_1_, student2_.cardId as cardId1_1_, student2_.name as name1_1_, student2_.age as age1_1_, student2_.team_id as team5_1_1_ from student students0_ inner join certificate certificat1_ on students0_.id=certificat1_.id left outer join student student2_ on certificat1_.id=student2_.id where students0_.team_id=?
由于team对students采用了延迟加载,所以在调用System.out.println(stu.getTeam().getStudents().size());的时候,进行SQL执行,同样使用了预先抓取,抓取对象是team中student对象所关联的certificate对象
2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值