数据库的字段:
结果:
password接收不到正确信息
原因:
UserMapper.xml中
<select id="getUserById" parameterType="int" resultType="com.xie.pojo.User">
select * from mybatis.user where id = #{id}
</select>
这里这句话,会自动转换成
<select id="getUserById" parameterType="int" resultType="com.xie.pojo.User">
select id,name,pwd from mybatis.user where id = #{id}
</select>
解决方法:
1、暴力起别名
<select id="getUserById" parameterType="int" resultType="com.xie.pojo.User">
select id,name,pwd as password from mybatis.user where id = #{id}
</select>
2、resultMap
结果集映射
- resultMap 元素是MyBatis中最重要最强大的元素
- ResultMap的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句,只需要描述它们的关系就行了
- ResultMap最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们
原来: id name pwd
改后: id name password
1、column是数据库中的字段,property是实体类中的属性
2、select 中的 resultMap 中的名字,要和 resultMap 中的 id 中的名字一样
3、type实际是com.xie.pojo.User,但是我在前面已经改过别名了
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace绑定一个对应的Dao接口(也可以叫Mapper接口)-->
<mapper namespace="com.xie.dao.UserMapper">
<resultMap id="UserMap" type="user">
<!-- column是数据库中的字段,property是实体类中的属性-->
<result column="id" property="id"></result>
<result column="name" property="name"></result>
<result column="pwd" property="password"></result>
</resultMap>
<select id="getUserById" resultMap="UserMap">
select * from mybatis.user where id = #{id}
</select>
</mapper>
- ResultMap最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们
所以上面可以改为:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace绑定一个对应的Dao接口(也可以叫Mapper接口)-->
<mapper namespace="com.xie.dao.UserMapper">
<resultMap id="UserMap" type="user">
<!-- column是数据库中的字段,property是实体类中的属性-->
<result column="pwd" property="password"></result>
</resultMap>
<select id="getUserById" resultMap="UserMap">
select * from mybatis.user where id = #{id}
</select>
</mapper>
只用列出改了名字的属性就行了