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 中,无论属性和字段是否相同,最好是所有都映射一下,否则某些场景会出问题 ~

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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yyhgo_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值