MyBatis

浅谈MyBatis结果集之resultMap 和 resultT

2020-09-10  本文已影响0人  Colors_boy

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>
结构暂且说这么多,有兴趣可以到官网自行了解

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>
上一篇下一篇

猜你喜欢

热点阅读