一、问题引入
- 属性名和字段名不一致的问题
数据库中的字段

实体类
public class User {
private int id;
private String name;
private String pds;
...
}
运行结果显示
字段不同出的查询结果为null

此时,我们回头看看sql语句
select * from mybatis.user where id=#{id}
select id,name,pd from mybatis.user where id=#{id}
那么我们如何解决呢?
- 起别名
<select id="SelectUserById" resultType="com.xiao.pojo.User">
select id,name,pd as pds from mybatis.user where id=#{id}
</select>
resultMap
结果集映射
<!-- 结果集映射,id=""和resultMap=""处的值一定要相同-->
<resultMap id="UserMap" type="User">
<!-- column是数据库的字段,property是实体中的属性-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pd" property="pds"/>
</resultMap>
<select id="SelectUserById" resultMap="UserMap">
select * from mybatis.user where id=#{id}
</select>
resultMap元素是 MyBatis 中最重要最强大的元素。- ResultMap 的设计思想是,对简单的语句根本不需要配置显示的结果映射,而对于复杂一点的语句,只需要描述语句之间的关系就可以了。
- ResultMap最优秀的地方在于,对它相当了解的情况下,就不需要显示的用到它们。
当数据库字段与Java实体类属性名不匹配时,查询结果可能出现null。解决方法包括使用别名或ResultMap。在SQL查询中使用别名如`pdaspds`,或者在ResultMap中定义字段与属性的映射关系,确保正确映射数据。
1153

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



