Search code examples
javaxmldatabasemybatisibatis

How to use partials or helpers in mybatis XML mapper?


I am using mybatis xml mapper. Most of the queries contains same types of filters. Is there any way to move these common filters in partial or helper as common place.

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>

Instead of using same filters every time is there any way to put this in common partial like:

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

then using this common partial every time I need it

Thanks in advance


Solution

  • You can try using <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>
    

    And then:

    <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>
    

    See also link if it doesn't work for your case.