目标: 能够自己实现学生班级案例,完成一对多查询
了解:
- collection 标签专门用来映射集合属性
- 实现分步查询的关键就是将 join on连接去掉,在collection添加select="查询的xml全类名,比立即加载多写一个接口"
注: 代码仅供理解
1.数据库表
##1. 创建班级表
create table t_clazz(
`id` int primary key auto_increment,
`name` varchar(50)
);
##1.2 插入班级信息
insert into t_clazz(`name`) values('javaEE20220228');
insert into t_clazz(`name`) values('javaEE20220325');
insert into t_clazz(`name`) values('javaEE20220420');
insert into t_clazz(`name`) values('javaEE20220515');
##1.3 创建学生表
create table t_student(
`id` int primary key auto_increment,
`name` varchar(50),
`clazz_id` int,
foreign key(`clazz_id`) references t_clazz(`id`)
);
##1.4 插入班级信息
insert into t_student(`name`,`clazz_id`) values('stu0228_1',1);
insert into t_student(`name`,`clazz_id`) values('stu0228_2',1);
insert into t_student(`name`,`clazz_id`) values('stu0228_3',1);
insert into t_student(`name`,`clazz_id`) values('stu0325_1',2);
insert into t_student(`name`,`clazz_id`) values('stu0325_2',2);
insert into t_student(`name`,`clazz_id`) values('stu0420_1',3);
2.config,lib
3.实现clazz的分步查询
public interface ClazzDAO {
public Clazz queryClazzById(int id);
/**
* 我要分两次查询,
* 一次只查常用数据,班级信息<br/>
* 当我需要使用学生信息的时候。再查询一次<br/>
*/
public Clazz queryClazzTwoStep(int id);
}
<resultMap type="com.zhuama.pojo.Clazz" id="queryClazzByIdForTwoStepLazy_resultMap">
<id column="id" property="id"/>
<result column="name" property="name"/>
<!--
collection 是专门映射集合的标签
property 属性设置你要设置和集合的属性名
ofType是 这个集合中每个元素的具体类型
select 是你要查询的语句
column 属性设置你要执行的select对应的查询语句需要的参数列
-->
<collection property="stuList" ofType="com.zhuama.pojo.Student"
select="com.zhuama.dao.StudentMapper.queryStudentsByClazzId"
column="id"
/>
</resultMap>
<!-- public Clazz queryClazzByIdForTwoStepLazy(int id); -->
<select id="queryClazzByIdForTwoStepLazy" resultMap="queryClazzByIdForTwoStepLazy_resultMap">
select id,name from t_clazz where id = #{id}
</select>
评论 (0)