mybatis 06 映射体系 03

  1. ResultMap配置
    1. 一对多
    2. 一对一
    3. 联合查询
    4. 懒加载
    5. 内部嵌套
    6. 外部嵌套

ResultMap配置

一对多

<resultMap id="blogMap" type="blog" autoMapping="true">
    <result column="title" property="title"/>
    <collection property="comments" column="id"  select="selectCommentsByBlogId" fetchType="eager"/>
</resultMap>

一对一

<resultMap id="commentMap" type="comment">
    <association property="blog" column="blog_id" select="selectBlogById" fetchType="eager"/>
</resultMap>

联合查询

  • 联合查询时自动映射默认关闭,autoMapping
  • 前缀匹配,columnPrefix
  • 限定不为空的列,notNullColumn,实现查询后java中二次过滤
    <resultMap id="blogMap" type="blog" autoMapping="true" >
      <id column="id" property="id" />
      <collection property="comments" ofType="comment"  autoMapping="true"  columnPrefix="comment_" >
          <association property="user" column="user" autoMapping="true"  notNullColumn="id" />
      </collection>
    </resultMap>

懒加载

<resultMap id="commentMap" type="comment">
    <association property="blog" column="blog_id" select="selectBlogById" fetchType="eager"/>
</resultMap>

<resultMap id="blogMap" type="blog" autoMapping="true">
    <result column="title" property="title"/>
    <collection property="comments" column="id" select="selectCommentsByBlogId" fetchType="eager"/>
</resultMap>

内部嵌套

<resultMap id="blogResult" type="Blog">
  <id property="id" column="blog_id" />
  <result property="title" column="blog_title"/>
  <association property="author" column="blog_author_id" javaType="Author" resultMap="authorResult"/>
</resultMap>

<resultMap id="authorResult" type="Author">
  <id property="id" column="author_id"/>
  <result property="username" column="author_username"/>
  <result property="password" column="author_password"/>
  <result property="email" column="author_email"/>
  <result property="bio" column="author_bio"/>
</resultMap>

<select id="selectBlog" resultMap="blogResult">
  select
    B.id            as blog_id,
    B.title         as blog_title,
    B.author_id     as blog_author_id,
    A.id            as author_id,
    A.username      as author_username,
    A.password      as author_password,
    A.email         as author_email,
    A.bio           as author_bio
  from Blog B left outer join Author A on B.author_id = A.id
  where B.id = #{id}
</select>

外部嵌套

将多表连接的 SQL 拆分,每个属性单独发一条 SQL:

<resultMap id="blogResult" type="Blog">
  <collection property="posts" javaType="ArrayList" column="id" ofType="Post" select="selectPostsForBlog"/>
</resultMap>

<select id="selectBlog" resultMap="blogResult">
  SELECT * FROM BLOG WHERE ID = #{id}
</select>

<select id="selectPostsForBlog" resultType="Post">
  SELECT * FROM POST WHERE BLOG_ID = #{id}
</select>

转载请注明来源。 欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。 可以在下面评论区评论,也可以邮件至 sharlot2050@foxmail.com。

文章标题:mybatis 06 映射体系 03

字数:584

本文作者:夏来风

发布时间:2020-06-19, 10:10:19

原始链接:http://www.demo1024.com/blog/mybatis-06-mapping-03/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。