<!--
一对一关联查询
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>
mybatis 查询方式 与效率高低
最新推荐文章于 2022-10-06 23:14:46 发布