映射方式
1、当列名和封装查询结果的类的属性名一一对应时:
- 这时MyBatis 有自动映射功能,将查询的记录封装到resultType 指定的类的对象中去
<mapper namespace="com.hanT.dao.UserDao">
<!--id对应接口中的方法名,resultType为返回结果的类型,要用类的全限定名-->
<select id="getUserList" resultType="com.hanT.pojo.User">
select * from mybatis.user
</select>
</mapper>
2、当列名和封装查询结果的类的属性名不对应时:
- 使用resultMap 标签,在标签中配置属性名和列名的映射关系
<resultMap type="cn.com.mybatis.pojo.User" id="UserResult">
<result property="username" column="name"/>
</resultMap>
<select id="findUserById" parameterType="java.lang.Long" resultMap="UserResult">
select id,name,email from t_user where id=#{id}
</select>
-
除了使用resultMap 标签之外, 第二种是使用sql 列的别名功能,将列的别名书写为对象属性名,也可以做到映射关系
Mybatis是如何将sql执行结果封装为目标对象并返回的
有了列名与属性名的映射关系后,Mybatis
通过反射创建对象(resultType有类的全路径),同时使用反射给对象的属性逐一赋值并返回,
那些找不到映射关系的属性,是无法完成赋值的。