<resultmap>

时间:2018-02-11 08:04:13

标签: spring-mvc spring-boot mybatis spring-mybatis

我做了很多研究但没有用。即使在Mybatis文档中它也说

  
    

id - ID结果;将结果标记为ID有助于提高整体绩效

         

result - 将正常结果注入字段或JavaBean属性

  

如果他们都可以注入一个字段,并且ID有性能提升,那么什么阻止我只使用id?这只是语义,我将主键映射到id标签?

我试过了:

<resultMap id="teacherMap" type="me.funmap.model.Teacher" autoMapping="true">
    <result column="t_id" property="t_id"/>
    <collection property="students" javaType="List" ofType="me.funmap.model.Student" autoMapping="true">
        <result column="s_id" property="s_id"/>
    </collection>
</resultMap>

<resultMap id="teacherMap" type="me.funmap.model.Teacher" autoMapping="true">
    <id column="t_id" property="t_id"/>
    <collection property="students" javaType="List" ofType="me.funmap.model.Student" autoMapping="true">
        <id column="s_id" property="s_id"/>
    </collection>
</resultMap>

声明

<select id="getAllTeacher" resultMap="teacherMap">
    SELECT teacher.t_id, t_name, s_id from teacher INNER JOIN student ON teacher.t_id = student.t_id
</select>

陈述的结果

&#13;
&#13;
       t_id    t_name           s_id

|          1 | teacher      |      38 |
|          1 | teacher      |      39 |
|          1 | teacher      |      40 |
|          1 | teacher      |      41 |
|          1 | teacher      |      42 |
|          1 | teacher      |      43 |
&#13;
&#13;
&#13;

因为我使用id或result,我得到相同的结果,resultMap和?之间的区别是什么?

2 个答案:

答案 0 :(得分:1)

不同之处在于,当使用id时,该字段将被视为实体的标识符。这只是mybatis创建的唯一id的一个实体,如果再次遇到它将被重用。

例如,请考虑以下查询结果:

t_id  | s_id
  1   |  1
  2   |  1

如果使用id,则会创建两个Teacher个实例,并且只会引用一个Student实例。

如果result用于每个Teacher实例,则会创建Student实例(具有相同的id==1)。在这种情况下,mybatis不知道那些学生行代表同一个实体。

答案 1 :(得分:0)

使用<id><result>获得相同结果的原因是:在<collection>中使用<resultMap>时,如果声明<id>( s),MyBatis将仅使用<id>对具有相同<id>值的行进行分组,如果您未声明任何<id>,它将使用全部{{ 1}}个将具有相同<result>(s)值的行分组。

如果结果是:

<result>

当您将 t_id t_name s_id | 1 | An | 38 | | 1 | An | 39 | | 1 | An | 40 | | 2 | An | 41 | | 2 | An | 42 | | 2 | An | 43 | 声明为

<resultMap>

您只有一名老师,有六个学生。

但是当您将<resultMap id="teacherMap" type="me.funmap.model.Teacher" autoMapping="true"> <id column="t_name" property="t_name"/> <result column="t_id" property="t_id"/> <collection property="students" javaType="List" ofType="me.funmap.model.Student" autoMapping="true"> <result column="s_id" property="s_id"/> </collection> </resultMap> 声明为

<resultMap>

您有两个老师,两个都有三个学生。