mybatis 查询方式 与效率高低

<!--
     一对一关联查询
     select s.id,s.name,s.age,t.name tname  from student s,teacher t where s.tid=t.id;
      -->

    <!--
        关联的嵌套 Select 查询
    问题:
        这种方式虽然很简单,但在大型数据集或大型数据表上表现不佳。这个问题被称为“N+1 查询问题”。 概括地讲,N+1 查询问题是这样子的:
            你执行了一个单独的 SQL 语句来获取结果的一个列表(就是“+1”)。
            对列表返回的每条记录,你执行一个 select 查询语句来为每条记录加载详细信息(就是“N”)。
    解决:
        MyBatis 能够对这样的查询进行延迟加载,因此可以将大量语句同时运行的开销分散开来。
        (例如: 我需要teacher这个对象的时候就会进行加载,如果不需要就不会立即加载(延迟加载))
         然而,如果你加载记录列表之后立刻就遍历列表以获取嵌套的数据,就会触发所有的延迟加载查询,性能可能会变得很糟糕。
    -->
    <!--  关联的嵌套 Select 查询  -->
    <resultMap id="studentMap" type="student">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
        <association property="teacher" column="tid" javaType="teacher" select="selectTeacherById">
        </association>
    </resultMap>

    <select id="findAll" resultMap="studentMap">
        select * from student;
    </select>
    <select id="selectTeacherById" parameterType="int" resultType="teacher"  >
        select * from  teacher where id=#{id};
    </select>


    <!--
        关联的嵌套  结果映射
		将结果直接映射 到实体类中
        第二种 方式效率比第一种 速度更高
     -->
    <resultMap id="studentMap1" type="student">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
        <association property="teacher" javaType="teacher">
            <id property="id" column="tid"/>
            <result property="name" column="tname"/>
        </association>
    </resultMap>
    <select id="selectAll" resultMap="studentMap1">
        select s.id,s.name,s.age,t.name tname ,t.id tid from student s,teacher t where s.tid=t.id;
    </select>

------------------------------------------------------------------
<!--  一对多  关联嵌套  结果映射    ofType 将数据封装到指定的泛型  -->
    <resultMap id="teacherMap" type="teacher">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <collection property="students" ofType="student" >
            <id property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="age" column="sage"/>
            <result property="tid" column="stid"/>
        </collection>
    </resultMap>
    <select id="selectTeacherById"  parameterType="int"  resultMap="teacherMap">
         select t.id ,t.name,s.id sid,s.name sname,s.age sage,s.tid stid
         from student s ,teacher t
         where s.tid=t.id and t.id=1;
    </select>

个人博客:https://www.xiaoxuya.top/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

白鸽呀

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

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

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

打赏作者

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

抵扣说明:

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

余额充值