10.【一对多 collection】:一个老师对多个学生

项目搭建过程

参考我的博客:10. 多对一、一对多 的实验环境搭建
 
其中实体类Teacher,Student变成下面的

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private int id;
    private String name;
    private int tid;
}

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
    private int id;
    private String name;

    //一个老师拥有多个学生
    private List<Student> students;
}

最终项目结构:

在这里插入图片描述



编写TeacherMapper接口方法

public interface TeacherMapper {

    //获取老师
    List<Teacher> getTeacher();

    //获取指定老师下的所有学生及老师的信息
    Teacher getTeacher2(@Param("tid") int id);

    Teacher getTeacher3(@Param("tid") int id);
}



编写TeacherMapper.xml的sql

1. --------------这个查出来,teacher为null

<select id="getTeacher" resultType="com.pojo.Teacher">
    select * from  teacher
</select>

console输出结果:

在这里插入图片描述

2. --------------按照查询嵌套处理【不推荐】

<select id="getTeacher3" resultMap="StudentTeacher2">
    select * from teacher where id=#{tid}
</select>

<resultMap id="StudentTeacher2" type="com.pojo.Teacher">
    <collection property="students" javaType="ArrayList" ofType="com.pojo.Student" select="getStudentByTeacherId" column="id"/>
</resultMap>

<select id="getStudentByTeacherId" resultType="com.pojo.Student">
    select * from student where tid=#{tid}
</select>

console输出结果:

在这里插入图片描述

3.--------------按照结果嵌套处理【推荐】

<select id="getTeacher2" resultMap="StudentTeacher">
SELECT s.id sid, s.name sname,t.name tname,t.id tid FROM student s, teacher t
WHERE s.tid = t.id AND tid = #{tid}
</select>

<resultMap id="StudentTeacher" type="com.pojo.Teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <!--复杂的属性,我们需要单独处理 对象:association 集合:collection
    javaType=""指定属性的类型!
    集合中的泛型信息,我们使用ofType获取
    -->
    <collection property="students" ofType="com.pojo.Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>

console输出结果:

在这里插入图片描述



TestCollection测试类【可不用看】

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你说的白是什么白_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值