(四)处理数据库与bean属性不一致情况

比如数据库的表结构:

bean结构:

在不修改表、bean结构基础上对映射文件进行修改即可(重命名)

一、在SQL中设置别名

stuCountry   stu_country  

<mapper namespace="test.studentMapper">
   
    <select id="selectUserByID" parameterType="int" resultType="test.student">
        select id,name,age,stuCountry stu_country from `tb_Student` where id = #{id}
    </select>
</mapper>

二、使用resultMap标签配置property属性和column属性的映射

注意此时用select *

 <select id="selectUserByID" parameterType="int" resultMap="stu">
         <!-- 当表和数据库属性不一致时,要重命名属性 -->
        select * from `tb_Student` where id = #{id}
    </select>
    <resultMap type="student" id="stu">
      <id property="id" column="id" />
      <result property="name" column="name" />
      <result property="age" column="age" />
      <result property="stu_country" column="stuCountry"/>
      <result property="stuHobbys" column="stu_Hobbys"/>
    </resultMap>

Q:mybatis是如何将SQL执行结果封装成目标对象并返回的?都有哪些映射形式?

第一种是使用<resultMap>标签,逐一定义数据库列名和对象属性名之间的映射关系

第二种是使用SQL列的别名功能,将列的别名书写成对象属性名

有了列名与属性名的映射关系后,mybatis通过反射创建对象,同时使用反射给对象的属性逐一赋值返回,那些找不到映射关系的属性,是无法完成赋值的

posted @ 2019-05-20 13:14  测试开发分享站  阅读(205)  评论(0编辑  收藏  举报