简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM