MyBatis -- resultType 和 resultMap
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
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 中无论属性和字段是否相同最好是所有都映射一下否则某些场景会出问题 ~
查询的结果就有值了如下图所示