一、问题引入
- 属性名和字段名不一致的问题
数据库中的字段
实体类
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最优秀的地方在于,对它相当了解的情况下,就不需要显示的用到它们。