zoukankan      html  css  js  c++  java
  • 【MyBatis】resultMap和resultType的区别

    mybatis中resultMap和resultType的区别

    mybatis中在查询进行select映射的时候,返回类型可以用resultType,也可以用resultMap。resultType是直接表示返回类型的,而resultMap则是对外部ResultMap的引用,但是resultType跟resultMap不能同时存在。

    public class User {

      private int id;

      private String username;

      private String hashedPassword;

    //省略setter/getter方法

    }

    使用resultType
    <select id="selectUsers" parameterType="int" resultType="com.someapp.model.User">

      select id, username, hashedPassword

      from some_table

      where id = #{id}

    </select>

    这些情况下,MyBatis 会在幕后自动创建一个 ResultMap,基于属性名来映射列到 JavaBean 的属性上。如果列名没有精确匹配,可以在列名上使用 select 字句的别名来匹配标签。

    使用resultMap
    <resultMap id="userResultMap" type="User">

      <id property="id" column="user_id" />

      <result property="username" column="username"/>

      <result property="password" column="password"/>

    </resultMap>

     

    <select id="selectUsers" parameterType="int" resultMap="userResultMap">

      select user_id, user_name, hashed_password

      from some_table

      where id = #{id}

    </select>

    不同
    resultType对应的是java对象中的属性,大小写不敏感;resultMap对应的是对已经定义好了id的resultTupe的引用,key是查询语句的列名,value是查询的值,大小写敏感;
    使用resultType的时候,要保证结果集的列名与java对象的属性相同,而resultMap则不用。
    另外,resultMap 元素,它是 MyBatis 中最重要最强大的元素,它能提供级联查询,缓存等功能。


  • 相关阅读:
    第十三周学习进度
    第二次冲刺阶段每日任务02
    第二次冲刺阶段每日任务01
    构建之法阅读笔记03
    找水王续
    第十二周学习进度
    找水王
    第十一周学习进度
    博客园的用户体验
    找水王1
  • 原文地址:https://www.cnblogs.com/zhuyeshen/p/12516548.html
Copyright © 2011-2022 走看看