美文网首页MyBatis
浅谈MyBatis结果集之resultMap 和 resultT

浅谈MyBatis结果集之resultMap 和 resultT

作者: Colors_boy | 来源:发表于2020-09-10 19:35 被阅读0次

resultType:先看代码

实体类:

public class Student{
    private Integer sid;
    private String sname;
    private String class;
  //省略getter and setter

}

xml文件:

<select id = selectStudentById resultType = "com.demo.model.Student">
select  sname, class
from student 
where 
  sid = #{id}
</select>

当实体类的属性名与数据库字段一致时可以采用resultType来配置映射。

resultMap:MyBatis中最重要最强大的元素,可以为复杂的sql语句提供复杂的映射结果(实际上也不会很复杂),先来了解简单的resultMap结构,以下是来自官网的 博客----文章 例子:

<resultMap id="blogResult" type="Blog">
  <id property="id" column="blog_id" />
  <result property="title" column="blog_title"/>
  <collection property="posts" ofType="Post">
    <id property="id" column="post_id"/>
    <result property="subject" column="post_subject"/>
    <result property="body" column="post_body"/>
  </collection>
</resultMap>
  • id:一个id结果,标记出作为 ID 的结果可以帮助提高整体性能
  • type:类的完全限定名, 或者一个类型别名
  • 属性id:唯一标识,用于标识一个结果映射
  • result: 注入到字段或 JavaBean 属性的普通结果
  • proerty:对应实体类中的属性
  • colunm:对应数据库中的字段(这与resultType的区别主要之一)
  • collection:一对多映射结果集(一个博客有多篇文章)
  • association:一对一映射结果(一个博客一个作者)
结构暂且说这么多,有兴趣可以到官网自行了解

XML映射文件


现在直接从实际场景中分析

实体类:

public class Blog{
    private Integer id;
    private String title;
    privat Integer authorId;

    private List<Post> posts;
    //省略getter and setter 方法
}

sql语句:

<select id="selectBlog" resultMap="blogResult">
  select
  B.id as blog_id,
  B.title as blog_title,
  B.author_id as blog_author_id,
  P.id as post_id,
  P.subject as post_subject,
  P.body as post_body,
  from Blog B
  left outer join Post P on B.id = P.blog_id
  where B.id = #{id}
</select>

resultMap:

collection 里面的内容是相当于把另一个结构体嵌进来,至于一对一的结果映射等下次再聊。

<resultMap id="blogResult" type="Blog">
  <id property="id" column="blog_id" />
  <result property="title" column="blog_title"/>
<!--配置文章属性-->
  <collection property="posts" ofType="com.demo.model.Post">
    <id property="id" column="post_id"/>
    <result property="subject" column="post_subject"/>
    <result property="body" column="post_body"/>
  </collection>
</resultMap>

相关文章

网友评论

    本文标题:浅谈MyBatis结果集之resultMap 和 resultT

    本文链接:https://www.haomeiwen.com/subject/orapektx.html