ResultMap结果集映射
引入原因
属性名与字段名不一致 。
则在mapper.xml映射文件中 mybatis无法将从数据库中查找出来的结果集的列名对应地转化为pojo类的对应属性。
解决方案
-
在SQL语句中 as 设置别名
<!--根据id查询用户--> <select id="getUserById" resultType="user" parameterType="int"> select id,name,password as pwd from user where id = #{id} <!--只需要取出来的结果集列名和pojp属性名一一对照即可--> </select>
-
resultMap结果集映射
<resultMap id="" type=""> <result column="" property=""></result> <result column="" property=""></result> <result column="" property=""></result> </resultMap>
代码实例
<mapper namespace="com.liu.dao.UserMapper"> <!--结果集映射--> <resultMap id="userMap" type="user"> <!--id对应resultMap--> <!--columu是表中的列名 property是对应的pojo属性名 --> <!--目的是构造 数据库表列名与pojo类属性名的一一映射--> <result column="id" property="id"></result> <result column="name" property="name"></result> <result column="password" property="pwd"></result> </resultMap> <!--根据id查询用户--> <!--使用resultMap结果集映射--> <select id="getUserById" resultMap="userMap" parameterType="int"> select * from user where id = #{id} </select> </mapper>
结果映射
resultMap
元素是 MyBatis 中最重要最强大的元素。它可以让你从 90% 的 JDBC ResultSets
数据提取代码中解放出来,并在一些情形下允许你进行一些 JDBC 不支持的操作。实际上,在为一些比如连接的复杂语句编写映射代码的时候,一份 resultMap
能够代替实现同等功能的数千行代码。ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
resultType实质是 隐式地建立了一个ResultMap, 使用查询出的列名与resultType中的属性做一一的对比,但是如果两者无法就无法使用。
因此resultType是一个简单的resultMap实现