MyBatis学习总结[4]-ResultMap子元素

官方文档


resultMap 元素有很多子元素和一个值得讨论的结构。 下面是 >resultMap 元素的概念视图

  • resultMap
    • constructor - 类在实例化时,用来注入结果到构造方法中
      • idArg - ID 参数;标记结果作为 ID 可以帮助提高整体效能
      • arg - 注入到构造方法的一个普通结果
    • id – 一个 ID 结果;标记结果作为 ID 可以帮助提高整体效能
    • result – 注入到字段或 JavaBean 属性的普通结果
    • association – 一个复杂的类型关联;许多结果将包成这种类型
      嵌入结果映射 – 结果映射自身的关联,或者参考一个
    • collection – 复杂类型的集
      嵌入结果映射 – 结果映射自身的集,或者参考一个
    • discriminator – 使用结果值来决定使用哪个结果映射
      • case – 基于某些值的结果映射
        嵌入结果映射 – 这种情形结果也映射它本身,因此可以包含很多相 同的元素,或者它可以参照一个外部的结果映射。

constructor标签

<constructor>
    <!-- 这里的int对应实体类构造方法参数的 Integer -->
   <idArg column="id" javaType="int"/>
   <arg column="username" javaType="String"/>
</constructor>
    //对应的构造方法
    public POJO(Integer id,String username){
    ...
    }

它将结果集映射到构造方法上,它根据参数的类型和顺序来确定构造方法。构造方法注入允许你在初始化时 为类设置属性的值,而不用暴露出公有方法。

discriminator标签

 <resultMap id="carDiscriminator" type="Car" >
            <!-- javaType 是需要被用来保证等价测试的合适类型,column指定需要鉴别的列,case可以指定结果集 -->
        <discriminator javaType="int" column="age">
            <case value="1" resultMap="car"/>
            <case value="2" resultType="car">
                <id property="id" column="id"/>
                <result property="name" column="name"/>
                <result property="money" column="money"/>
                <result property="age" column="age"/>
                <result property="uId" column="uId"/>
                <association property="user" resultMap="me.dao.UserDao.User" columnPrefix="u_"/>
            </case>
        </discriminator>

association标签

    <resultMap type="Car" id="carWithUser" extends="car">
        <!-- columnPrefixw为resultMap的每个column添加前缀 -->
        <association property="user" resultMap="me.dao.UserDao.User" columnPrefix="u_"/>
        <!-- select指定嵌套的查询的Id,column指定根据哪列来嵌套查询 -->
        <association property="car" column="id" select="getCar" />
    </resultMap>

collection标签

  <resultMap type="User" id="UserWithCarAndDog">
    <id property="id" column="id"/>
    <result property="name" column="name"/>
    <result property="age" column="age"/>
    <!-- select指定嵌套的查询的Id,column指定根据哪列来嵌套查询 -->
    <collection property="dogs" column="id" select="selectDogsWithUid"/>
     <!-- columnPrefixw为resultMap的每个column添加前缀 -->
     <collection property="dogs" ofType="Dog" resultMap="dog" columnPrefix="dog_"/>
  </resultMap>
原文地址:https://www.cnblogs.com/A-yes/p/9894181.html