如何在MyBatis中使用两个不同的resultMaps重用相同的SELECT查询?

时间:2017-07-26 20:34:56

标签: java spring mybatis

我有一个映射器resultMap,它有两个我需要内联选择的集合

<collection property="companies" ofType="Company" column="user_id" select="selectCompanies"/>
<collection property="companyGroups" ofType="CompanyGroup" column="user_id" select="selectCompanyGroups"/>

两个集合的查询完全相同,但生成的映射彼此非常不同。有没有办法可以使用相同的选择与两个不同的resultMaps

我必须内联运行这些查询,因为如果它是主查询的一部分,由于左连接,它将导致额外的几千条记录。

我不能使用SQL,因为它只允许静态参数解析,而不是动态。

1 个答案:

答案 0 :(得分:3)

  

有没有办法可以使用两个不同resultMap的相同选择?

是的,您可以使用相同的选项,使用两个不同的resultMap

<mapper namespace="com.example.PersonRepository">
    <!-- The common re-usable SELECT query -->
    <sql id="select-part">
        SELECT first_name, last_name, ...other attributes... 
        FROM table
        <!-- You may use dynamic parameters here the same way as in a regular query -->
        <where>
            <if test="searchParams.firstName != null">
                first_name = #{searchParams.firstName}
            </if>
            <if test="searchParams.lastName != null">
                and last_name = #{searchParams.lastName}
            </if>
        </where>
    </sql>

    <!-- Method List<Type1> getAsType1(SearchParams searchParams) -->
    <select id="getAsType1" resultMap="map1">
        <include refid="select-part"/>
    </select>

    <!-- Method List<Type2> getAsType2(SearchParams searchParams) -->
    <select id="getAsType2" resultMap="map2">
        <include refid="select-part"/>
    </select>

    <resultMap id="map1" type="Type1">
        ...
    </resultMap>

    <resultMap id="map2" type="Type2">
        ...
    </resultMap>
</mapper>

不要担心whereand条款,MyBatis会handle them correctly

您的Java代码可能如下所示:

package com.example;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
// Other imports

@Repository
public interface PersonRepository {
    public List<Type1> getAsType1(@Param("searchParams") SearchParams searchParams);
    public List<Type2> getAsType2(@Param("searchParams") SearchParams searchParams);
}

SearchParams只是一个包含firstNamelastName等的POJO。