解决属性名和字段名不一致的问题
1、问题
数据库中的字段

实体类字段和数据库不一致

测试出现问题

测试执行的sql语句
select * from user where id=#{id}
//类型处理器
select id,username,birthday,sex,address from user where id=#{id}
解决方法:
- 起别名
<!--根据id查询用户-->
<select id="getUserById" parameterType="int" resultType="com.chif.pojo.User">
select id,username,birthday,sex,address as 'add' from user where id=#{id}
</select>
2、resultMap
结果集映射
id username birthday sex address
id username birthday sex add
<!--结果集映射-->
<resultMap id="UserMap" type="User">
<!--column 数据库中的字段,property 实体类中的属性-->
<result property="id" column="id"></result>
<result property="username" column="username"></result>
<result property="birthday" column="birthday"></result>
<result property="sex" column="sex"></result>
<result property="add" column="address"></result>
</resultMap>
<!--根据id查询用户-->
<select id="getUserById" parameterType="int" resultMap="UserMap">
select * from user where id=#{id}
</select>
resultMap元素是 MyBatis 中最重要最强大的元素。resultMap的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
本文详细解析了在使用MyBatis框架时遇到的实体类字段与数据库字段不一致的问题,通过起别名和使用resultMap元素来实现属性映射,确保了数据的正确读取。

1万+

被折叠的 条评论
为什么被折叠?



