MyBatis -- resultType 和 resultMap

一、返回类型:resultType

绝⼤数查询场景可以使用 resultType 进⾏返回,如下代码所示:

    <select id="getNameById" resultType="java.lang.String">
        select username from userinfo where id=#{id}
    </select>

返回自定义实体类也是同样 ~

它的优点是使用方便,直接定义到某个实体类即可。

但在很多场景中,实体类属性名和数据库表字段名并不相同,这时候就要使用 resultMap 了!

二、返回字典映射:resultMap

resultMap 使用场景:

  • 字段名称和程序中的属性名不同的情况,可使用 resultMap 配置映射;
  • ⼀对⼀和⼀对多关系可以使用 resultMap 映射并查询数据。

属性名和字段名不同的情况

数据库表字段名:

在这里插入图片描述

实体类属性名:

在这里插入图片描述

mapper.xml 代码如下:

    <select id="getUserById" resultType="com.example.demo.model.User">
        select * from userinfo where id=#{id}
    </select>

查询的结果如下:

在这里插入图片描述

这个时候就需要使用 resultMap 了,resultMap 的使用如下:
(在相应 .xml 文件中配置)
在这里插入图片描述

mapper.xml:

    <resultMap id="BaseMap" type="com.example.demo.model.User">
        <id column="id" property="id"></id>
        <result column="username" property="username"></result>
        <result column="password" property="pwd"></result>
    </resultMap>
    <select id="getUserById" resultMap="com.example.demo.mapper.UserMapper.BaseMap">
        select * from userinfo where id=#{id}
    </select>

注意:

  • id 命名规范为 大驼峰 ~
  • 在 resultMap 中,无论属性和字段是否相同,最好是所有都映射一下,否则某些场景会出问题 ~

查询的结果就有值了,如下图所示:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/yyhgo_/article/details/128713697