如何在 mybatis XML mapper 中使用 partials 或 helpers?

How to use partials or helpers in mybatis XML mapper?

我正在使用 mybatis xml 映射器。 大多数查询包含相同类型的过滤器。 有什么方法可以将这些公共过滤器移动到部分或助手中作为公共位置。

select id="getMaxData" resultMap="Result">
    SELECT IFNULL(MAX(data), 0) AS data
    FROM well_data WHERE result = 'foo' AND data > 0

    <if test="test1 != '' ">
        AND test1 = #{test1}
    </if>
    <if test="test2 != '' ">
        AND test2 = #{test2}
    </if>
    <if test="test3 != '' ">
        AND test3 = #{test3}
    </if>
</select>

select id="getAverageData" resultMap="Result">
    SELECT IFNULL(AVG(data), 0) AS data
    FROM well_data WHERE result = 'foo' AND data > 0

    <if test="test1 != '' ">
        AND test1 = #{test1}
    </if>
    <if test="test2 != '' ">
        AND test2 = #{test2}
    </if>
    <if test="test3 != '' ">
        AND test3 = #{test3}
    </if>
</select>

不是每次都使用相同的过滤器,有什么办法可以将其放在公共部分中,例如:

common partial
    <if test="test1 != '' ">
        AND test1 = #{test1}
    </if>
    <if test="test2 != '' ">
        AND test2 = #{test2}
    </if>
    <if test="test3 != '' ">
        AND test3 = #{test3}
    </if>

然后每次需要时都使用这个通用部分

提前致谢

您可以尝试使用 <include/>:

<sql id="common-constraints">
    <if test="test1 != '' ">
        AND test1 = #{test1}
    </if>
    <if test="test2 != '' ">
        AND test2 = #{test2}
    </if>
    <if test="test3 != '' ">
        AND test3 = #{test3}
    </if>
</sql>

然后:

<select id="getMaxData" resultMap="Result">
    SELECT IFNULL(MAX(data), 0) AS data
    FROM well_data WHERE result = 'foo' AND data > 0
    <include refid="common-constraints"/>
</select>

如果它不适用于您的情况,另请参阅 link