(七)解决属性名和字段名不一致的问题ResultMap
之前在编写代码的时候,类的属性名要和数据库的字段严格一一对应,否则就会查不出来,此时ResultMap提供了解决方案。
ResultMap能够实现数据库字段到属性名的映射。
环境
-
数据库
user(id,name,pwd)
-
自定义类
User(id,name,password)
问题
现在如果直接进行查询的话,会发现password = null,这是因为数据库中的字段没有和类的属性名一一对应
解决方案
使用ResultMap,可以实现属性与字段值的手动设置
<resultMap id="userMap" type="top.zhang.pojo.User">
<result column="id" property="id"></result>
<result column="name" property="name"></result>
<result column="pwd" property="password"></result>
</resultMap>
<select id="getUserById" parameterType="int" resultMap="userMap">
select * from mybatis.user where id=#{id}
</select>
如上所示:
- id表示下面resultMap要使用的id
- type表示数据库表对应的对象
- column表示数据库字段
- property表示对象的属性
以上,完成了数据库字段和属性名的映射操作。