MyBatis中多表查询(多表查询语句实现)重点

–查询所有学生所在班级的信息(一对一)
–班级查询学生的操作(一对多)
–遇到的问题:
查询的SQL语句非常的简单,但是如何把查询的数据接受这个就是一个问题
[1]把每一个实体中的字段拿出来组建成一个新的实体 返回还是resultType
存在的问题:映射的内容会出现重复的字段
[2] resultMap:映射的操作
接口
StudentMapper.java

public interface StudentMapper {
    //多表查询操作
    List<Student>  selectAll2();
}

ClazzMapper.java

public interface ClazzMapper {
    //多表查询班级学生信息
    List<Clazz>   selectAll2();
}

XML
StudentMapper.xml

    <select id="selectAll2"  resultMap="rm2">
    SELECT  *  FROM  student  s  JOIN   clazz   c  ON  s.clazzno=c.clazzno

    </select>
    <resultMap id="rm2" type="student">
        <!--注意:书写的每一个值就是接受数据库查询的数据
                  所以想要接受的数据的字段不可以省去
        -->
        <id column="sid" property="sid"></id>

        <result column="sname" property="sname"></result>

        <result column="clazzno" property="clazzno"></result>

        <association property="cla" javaType="clazz"> //‘cla’student表中的clazz对象

            <id column="clazzno" property="clazzno"></id>

            <result column="cname" property="cname"></result>
        </association>
    </resultMap>

Clazzmapper.xml

    <select id="selectAll2" resultMap="rm2">

     SELECT  *  FROM  student  s  JOIN   clazz   c  ON  s.clazzno=c.clazzno

    </select>
    
    <resultMap id="rm2" type="clazz">
        <id column="clazzno" property="clazzno"></id>

        <result column="cname" property="cname"></result>

        <collection property="li" ofType="student">  //‘li’ clazz表中的学生集合 

            <id column="sid" property="sid"></id>

            <result column="sname" property="sname"></result>

            <result column="clazzno" property="clazzno"></result>

        </collection>
    </resultMap>

测试

        //[4]执行方法

        StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);

        ClazzMapper  claMapper = sqlSession.getMapper(ClazzMapper.class);

        //查询所有学生所在的班级的信息

        /*List<Student> list = stuMapper.selectAll2();

        for(Student  student:list){

            System.out.println(student);
        }*/

        List<Clazz> list = claMapper.selectAll2();

        for(Clazz  clazz:list){

            System.out.println(clazz);
        }

4、Auto_Mapping
数据注入的方式
[1]自动注入方式 Auto_Mapping (自己封装的实体属性和数据库的字段是一样的情况Mybatis会自动的注入)
[2]手动注入的方式 resultMap
作用:解决自己做的实体的封装和数据库的字段不一致的问题
5、resultType和resultMap使用场景
[1]如果你做的是单表的查询并且封装的实体和数据库的字段一一对应 resultType
[2]如果实体封装的属性和数据库的字段不一致 resultMap
[3]使用的是多表的联合查询 resultMap
[4]使用N+1查询的时候 resultMap

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

AloneDrifters

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

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

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

打赏作者

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

抵扣说明:

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

余额充值