mybatis的嵌套查询和嵌套结果的区别

嵌套查询(Nested Query)是指在 XML 映射文件中通过 <select> 标签嵌套定义查询语句,嵌套结果(Nested Result)是指通过 resultMap 的嵌套引用来处理一对一或一对多映射关系

<select id="selectUserWithPosts" resultMap="userPostsMap">
  SELECT * FROM user WHERE id = #{id}
</select>
 
<resultMap id="userPostsMap" type="User">
  <id property="id" column="id"/>
  <result property="username" column="username"/>
  <collection property="posts" ofType="Post">
    <select id="selectPostsOfUser" resultType="Post">
      SELECT * FROM post WHERE user_id = #{id}
    </select>
  </collection>
</resultMap>

嵌套结果

<resultMap id="userPostsMap" type="User">
  <id property="id" column="user_id"/>
  <result property="username" column="user_name"/>
  <collection property="posts" ofType="Post">
    <id property="id" column="post_id"/>
    <result property="title" column="post_title"/>
    <result property="content" column="post_content"/>
  </collection>
</resultMap>

注意:嵌套结果由于多表联合查询(1-n的关系),无法用户分页场景(除非内存分页)

posted @ 2024-04-16 18:56  zbjice  阅读(295)  评论(0)    收藏  举报