【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方法 

}

  1. 使用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 字句的别名来匹配标签。

  1. 使用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>

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

猜你喜欢

转载自blog.csdn.net/qq_33591903/article/details/81075243