MyBatis查询时属性名和字段名不一致问题的解决方法
作者:weixin_44953227 时间:2023-10-23 16:56:36
问题
当我们数据库中的字段和实体类中的字段不一致的时候,查询会出问题
数据库字段是 pwd
id name pwd
1 张三 123456
2 李四 123456
3 王五 123456
4 赵六 123456
实体类字段是 password
public class User {
private int id;
private String name;
private String password;
}
查出来结果发现, password 是 null
User{id=1, name='张三', password='null'}
User{id=2, name='李四', password='null'}
User{id=3, name='王五', password='null'}
User{id=4, name='赵六', password='null'}
原因是类型处理器
select * from user
// 类型处理器:我们查询 select * 实际是查询 select id,name,pwd
select id,name,pwd from user
解决办法
resultMap:结果集映射
sql起别名
select id,name,pwd as password from user
解决方案:resultMap
结果集映射:https://mybatis.org/mybatis-3/zh/sqlmap-xml.html#Result_Maps
resultMap 元素是 MyBatis 中最重要最强大的元素
ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了
我们只需要在Mapper.xml 中加入结果集映射即可,且只加需要映射的字段即可
<mapper namespace="com.pro.dao.UserMapper">
<!--id: 下面select语句中resultMap绑定的(标识符/名称), type: 我们的实体类-->
<resultMap id="UserMap" type="User">
<!--column: 对应数据库中的字段, property: 对应实体类中的属性-->
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserList" resultMap="UserMap">
select * from users
</select>
</mapper>
总结
来源:https://blog.csdn.net/weixin_44953227/article/details/112648481
标签:mybatis,查询,属性名
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Intellij IDEA 2017新特性之Spring Boot相关特征介绍
2023-06-22 15:13:02
![](https://img.aspxhome.com/file/2023/0/88140_0s.gif)
详解关于java文件下载文件名乱码问题解决方案
2021-07-05 15:27:04
![](https://img.aspxhome.com/file/2023/4/106144_0s.png)
Java中string和int的互相转换问题
2023-07-26 14:27:34
Java spring AOP基础
2022-08-10 12:39:25
Java中常见的查找算法与排序算法总结
2021-07-14 13:21:23
![](https://img.aspxhome.com/file/2023/3/62753_0s.png)
Prometheus 入门教程之SpringBoot 实现自定义指标监控
2022-08-02 12:58:54
![](https://img.aspxhome.com/file/2023/7/67487_0s.jpg)
unity实现贪吃蛇游戏
2022-05-28 07:07:51
![](https://img.aspxhome.com/file/2023/7/98287_0s.jpg)
c#简单工厂、工厂方法与抽象工厂的区别分析
2021-11-30 04:39:47
SpringBoot集成支付宝沙箱支付(支付、退款)
2022-02-15 16:50:52
Kotlin中空判断处理操作实例
2023-01-16 00:45:19
![](https://img.aspxhome.com/file/2023/1/128941_0s.png)
Android 状态管理之Lifecycle浅析
2023-06-27 21:34:05
![](https://img.aspxhome.com/file/2023/5/110725_0s.webp)
Java C++ 算法题解leetcode669修剪二叉搜索树示例
2022-09-22 04:56:13
![](https://img.aspxhome.com/file/2023/9/61119_0s.png)
Java进程间通信之消息队列
2023-05-24 01:44:27
![](https://img.aspxhome.com/file/2023/3/97953_0s.png)
IDEA实现添加 前进后退 到工具栏的操作
2021-08-30 21:34:48
![](https://img.aspxhome.com/file/2023/7/62687_0s.jpg)
SpringBoot封装响应数据实现过程详解
2023-01-17 21:32:51
![](https://img.aspxhome.com/file/2023/5/88215_0s.png)
Android定时器和倒计时实现淘宝秒杀功能
2023-01-18 02:17:04
![](https://img.aspxhome.com/file/2023/3/137153_0s.png)
Mybatis实现关联关系映射的方法示例
2022-09-18 05:36:12
![](https://img.aspxhome.com/file/2023/9/128909_0s.jpg)
WPF实现环(圆)形菜单的示例代码
2022-05-07 18:46:34
![](https://img.aspxhome.com/file/2023/1/96351_0s.gif)
C#中Convert.ToDecimal()报错问题的解决
2022-05-09 06:05:56
SpringBoot 二维码生成base64并上传OSS的实现示例
2023-05-12 04:41:33