在学习MyBatis中我们的pojo类属性名称始终与数据库的名称一致,可是如果数据库字段足够多的时候,我们无法使pojo类的属性名与数据库字段名一致时,将采用ResultMap来解决
测试出现null值
在mapper.xml中
<select id="getUserById" parameterType="int" resultType="User">
select * from user where id = #{id}
</select>
完整语句应为:
/*
select id,name,password from user where id = #{id}
*/
第一个解决方法,在sql语句中我们可以使用as进行取别名
<select id="getUserById" parameterType="int" resultType="User">
select id,name,password as pwd from user where id = #{id}
</select>
结果为:
但是这个方法并不是最优解
第二个方法:ResultMap映射
在Mapper.xml中写
<resultMap id="getUserMap" type="User">
<!--
column:数据库中的字段名称
property:pojo类中的属性名称
-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="password" property="pwd"/>
</resultMap>
<select id="getUserById" parameterType="int" resultMap="getUserMap">
select * from user where id = #{id}
</select>
测试结果为: