在mybatis中的单次提取中为两个不同的查询重用相同的ResultMap

时间:2016-05-12 06:11:59

标签: mybatis ibatis spring-mybatis

要求:我需要从两个查询中获取部分数据,并将数据填充到单个结果图中。

问题:当我们从一个查询中获取数据时,它能够将数据加载到resultmap中,但是当我将第二个查询中的数据加载到同一个结果映射中时,数据会被刷新。 / p>

我想当我们使用相同的resultmap时,它会创建一个新地图。有一种方法可以在mapper.xml中的会话中提供结果图。

代码

    public Details { 
      private Term term;
    }

    public Term {
       private String name;
       private String location;
    }

mapper.xml

    <?xml version="1.0" encoding="UTF-8" ?>
            <!DOCTYPE mapper
              PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
              "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="org.project.example.MyMapper">
              <select id="select_form" parameterType="long" resultMap="select-result">
                    select id,name from details where id= #{id}
              </select>
              <select id="select_form_ext" parameterType="long" resultMap="select-result-ext">
                    select id,location from term where id= #{id}
               </select>
               <resultMap id="select-result" type="DetailsDto">
                        <association property="TermDto" column="ID"  select="select_form_ext"  />
                        <association property="TermDto" column="ID"  resultMap="select-main-result"  />
               </resultMap>                   
               <resultMap id="select-result-ext" type="TermDto">
                      <result property="location" column="LOCATION" />
               </resultMap>                      
               <resultMap id="select-main-result" type="TermDto" >
                       <result property="name" column="NAME" />
               </resultMap>
    </mapper>

1 个答案:

答案 0 :(得分:0)

请尝试使用以下步骤。

Step1#:<resultMap id="select-result" >...

中删除以下行select-result-ext

Step2#:修改ResultMap <resultMap id="select-result-ext" type="TermDto"> <result property="location" column="LOCATION" /> <result property="name" column="NAME" /> </resultMap> ,如下所示

<resultMap id="blogResult" type="Blog">
  <association property="author" column="author_id" javaType="Author" select="selectAuthor"/>
</resultMap>

<select id="selectBlog" resultMap="blogResult">
  SELECT * FROM BLOG WHERE ID = #{id}
</select>

<select id="selectAuthor" resultType="Author">
  SELECT * FROM AUTHOR WHERE ID = #{id}
</select>

Step3#:执行/运行应用程序并检查结果。

<强>例如#:

 public partial class catagory
{
    public int id { get; set; }
    public string cat_name { get; set; }
    public Nullable<int> measure_type { get; set; }
    public Nullable<int> active { get; set; }
    public Nullable<int> parent_cat { get; set; }
    public Nullable<int> display_order { get; set; }
    public string cat_image { get; set; }
}