软件编程
位置:首页>> 软件编程>> java编程>> MyBatis查询时属性名和字段名不一致问题的解决方法

MyBatis查询时属性名和字段名不一致问题的解决方法

作者:weixin_44953227  发布时间:2023-10-23 16:56:36 

标签:mybatis,查询,属性名

问题

当我们数据库中的字段和实体类中的字段不一致的时候,查询会出问题

数据库字段是 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

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com