简体   繁体   中英

How to query the value of a static parameter of MyBatis <sql> fragment?

Is it possible in MyBatis to combine statically parametrized <sql> reusable fragments with <if> dynamic SQL ?

How to query the value of a static (= not coming from Java method, but entered directly in the mapper XML) parameter of MyBatis <sql> fragment?

The question is not how to compare String values in MyBatis, but how to query the value of a static parameter .

I am trying to call the reusable element select-part with a static parameter source .

I have tried various ways of writing the <if test="..."> condition but all fail:

  • <if test="source == 'active'">
  • <if test="${source} == 'active'">
  • <if test="#{source} == 'active'">

The simplified mapper XML is something like this:

<sql id="select-part">
    SELECT d.field1, d.field2, ..., d.fieldN
    <if test="${source} == 'active'">
        , null AS archivedDate
        FROM active_table d
    </if>
    <if test="${source} == 'archive'">
        , d.achived AS archivedDate
        FROM archive_table d
    </if>
    LEFT JOIN ...
    ORDER BY ...
</sql>

<select id="fetchData" resultMap="Data">
    <include refid="select-part">
        <property name="source" value="active"/>
    </include>
    UNION ALL
    <include refid="select-part">
        <property name="source" value="archive"/>
    </include>
</select>

Unfortunately, current implementation has a "bug" that it does not replace placeholders in XML attributes in the SQL fragments. Only placeholders in text nodes are replaced. I consider this as a bug in the implementation which should be fixed. I have implemented that in my fork: https://github.com/kmoco2am/mybatis-3 and I will try to push into the original repository.

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