Chapter 07

Dynamic SQL

Dynamic SQL is the feature that makes MyBatis worth choosing. Nine tags let you build any query shape at runtime while every value stays a bound parameter — no concatenation, no injection surface.

⏱ 22 min readLevel: intermediateMost-referenced chapter
Pipeline showing parameters evaluated by OGNL, applied to a SqlNode tree, producing a BoundSql executed over JDBC
Tags are evaluated at execution time against the parameter object, producing a BoundSql.

The tag set

TagDoes
<if>Include the body when the test is true
<choose>/<when>/<otherwise>Switch — first match wins
<where>Emit WHERE only if there is content; strip a leading AND/OR
<set>Emit SET; strip the trailing comma
<trim>The general form of both of the above
<foreach>Iterate a collection, array or map
<bind>Create a local variable from an OGNL expression
<sql>/<include>Reuse a fragment (chapter 4)

if

UserMapper.xml
<select id="search" resultType="User">
  SELECT id, user_name, email, status
  FROM app_user
  WHERE 1 = 1
  <if test="userName != null and userName != ''">
    AND user_name LIKE #{userName}
  </if>
  <if test="status != null">
    AND status = #{status}
  </if>
</select>

WHERE 1 = 1 works and you will see it everywhere, but it is a workaround for a problem <where> solves properly. Some query planners also treat it as an extra predicate. Prefer the next section.

where

UserMapper.xml
<select id="search" resultType="User">
  SELECT id, user_name, email, status
  FROM app_user
  <where>
    <if test="userName != null and userName != ''">
      AND user_name LIKE #{userName}
    </if>
    <if test="status != null">
      AND status = #{status}
    </if>
    <if test="createdAfter != null">
      AND created_at &gt;= #{createdAfter}
    </if>
  </where>
  ORDER BY id
</select>
ParametersGenerated SQL
all nullSELECT … FROM app_user ORDER BY id
status only… WHERE status = ? ORDER BY id
userName + status… WHERE user_name LIKE ? AND status = ? ORDER BY id
Only the LEADING connector is removed

<where> strips a single AND or OR from the start of the assembled content. It does not clean up a trailing one. Writing user_name LIKE #{name} AND and hoping the tag tidies up produces a syntax error.

choose / when / otherwise

Exactly one branch is emitted — a SQL switch.

UserMapper.xml
<select id="findByAnyIdentifier" resultType="User">
  SELECT id, user_name, email FROM app_user
  <where>
    <choose>
      <when test="id != null">
        AND id = #{id}
      </when>
      <when test="email != null">
        AND email = #{email}
      </when>
      <when test="userName != null">
        AND user_name = #{userName}
      </when>
      <otherwise>
        AND 1 = 0        <!-- no identifier supplied: return nothing -->
      </otherwise>
    </choose>
  </where>
</select>

That <otherwise> is a deliberate safety net. Without it, a caller who passes no identifier would get the whole table.

set

UserMapper.xml
<update id="updateSelective">
  UPDATE app_user
  <set>
    <if test="userName != null">user_name = #{userName},</if>
    <if test="email    != null">email     = #{email},</if>
    <if test="status   != null">status    = #{status},</if>
    version = version + 1
  </set>
  WHERE id = #{id}
</update>

Keep an unconditional assignment (here version = version + 1) at the end. It guarantees the SET clause is never empty, which would otherwise be a syntax error when every field is null.

trim — the general form

<where> and <set> are just preconfigured trims. Use <trim> when you need a different prefix or suffix.

equivalents
<!-- <where> is exactly this -->
<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>

<!-- <set> is exactly this -->
<trim prefix="SET" suffixOverrides=",">
  ...
</trim>
a dynamic INSERT built with two trims
<insert id="insertSelective" useGeneratedKeys="true" keyProperty="id">
  INSERT INTO app_user
  <trim prefix="(" suffix=")" suffixOverrides=",">
    <if test="userName != null">user_name,</if>
    <if test="email    != null">email,</if>
    <if test="status   != null">status,</if>
  </trim>
  VALUES
  <trim prefix="(" suffix=")" suffixOverrides=",">
    <if test="userName != null">#{userName},</if>
    <if test="email    != null">#{email},</if>
    <if test="status   != null">#{status},</if>
  </trim>
</insert>
The trailing space matters

prefixOverrides="AND |OR " includes a space after each keyword, and multiple candidates are separated by |. Omit the space and you would also strip the AND out of a column named ANDROID_ID.

foreach

attributes
<foreach collection="ids"   <!-- name of the collection parameter -->
         item="id"          <!-- current element                  -->
         index="i"          <!-- position, or key for a Map       -->
         open="("           <!-- emitted before the first element -->
         separator=","      <!-- between elements                 -->
         close=")">         <!-- after the last element           -->
  #{id}
</foreach>

IN clauses

UserMapper.xml
<select id="findByIds" resultType="User">
  SELECT id, user_name, email FROM app_user
  WHERE id IN
  <foreach collection="ids" item="id" open="(" separator="," close=")">
    #{id}
  </foreach>
</select>

With ids = [7, 9, 11] this becomes WHERE id IN (?, ?, ?).

The collection attribute name

Method signaturecollection value
find(List<Long> ids)list (or collection)
find(Long[] ids)array
find(@Param("ids") List<Long> ids)ids
find(UserQuery q) with q.getIds()ids
find(Map<String,Object> m)the map key

Always use @Param. Relying on the magic list name produces mappers that break the moment someone adds a second argument.

Multi-row inserts and OR groups

UserMapper.xml
<!-- multi-row insert -->
<insert id="insertBatch">
  INSERT INTO app_user (user_name, email, status) VALUES
  <foreach collection="users" item="u" separator=",">
    (#{u.userName}, #{u.email}, #{u.status})
  </foreach>
</insert>

<!-- composite key lookup: (a,b) OR (c,d) -->
<select id="findByPairs" resultType="Order">
  SELECT * FROM customer_order
  WHERE
  <foreach collection="pairs" item="p" separator=" OR " open="(" close=")">
    (user_id = #{p.userId} AND status = #{p.status})
  </foreach>
</select>

<!-- iterating a Map: index is the key -->
<update id="updateColumns">
  UPDATE app_user
  <set>
    <foreach collection="values" index="column" item="value" separator=",">
      ${column} = #{value}
    </foreach>
  </set>
  WHERE id = #{id}
</update>
Two hard limits

Empty collection → IN () → syntax error. Guard in Java.
Huge collection → parameter-limit exception (PostgreSQL 65,535, SQL Server 2,100) and a query plan that takes longer to compile than to run. Chunk at about 500–1,000, or join against a temporary table.

bind

Creates a variable in the OGNL context. The canonical use is building a LIKE pattern without concatenating in SQL — which keeps the statement portable, since ||, + and CONCAT() differ per vendor.

UserMapper.xml
<select id="searchByName" resultType="User">
  <bind name="pattern" value="'%' + userName + '%'"/>
  SELECT id, user_name, email FROM app_user
  WHERE user_name LIKE #{pattern}
</select>

The value is still bound as a parameter — bind only builds the Java string. For a case-insensitive search, combine it with a function: WHERE LOWER(user_name) LIKE LOWER(#{pattern}).

Escape LIKE wildcards

A user searching for 50% or a_b will match far more than they expect. Sanitise in Java before the query:

String safe = raw.replace("!", "!!")
                 .replace("%", "!%")
                 .replace("_", "!_");
// SQL: WHERE user_name LIKE #{pattern} ESCAPE '!'

OGNL rules that bite

test expressions are OGNL, not Java. Four differences cause almost every bug report:

ExpressionResultExplanation
test="status == 'Y'"✗ often false Single quotes make a char. Comparing a String to a char fails. Write status == "Y".toString() or 'Y'.toString().equals(status).
test="name != null and name != ''"✓ Use and/or, not &&/|| (&& also needs XML escaping).
test="list != null and list.size() > 0"✓ .size() works on collections; .length works on arrays and strings.
test="user.address.city != null"✗ NPE risk OGNL does not short-circuit nested navigation. Check each level, or use <bind> first.
test="type == @com.x.Type@ADMIN"✓ Static field access uses @class@field.
test="flag" where flag is Boolean✓ Null is treated as false.

A complete search mapper

Everything from this chapter, applied to a realistic admin search screen.

UserQuery.java
public class UserQuery {
    private String  nameLike;
    private List<String> statuses;
    private LocalDate createdFrom;
    private LocalDate createdTo;
    private Boolean hasOrders;
    private String  sortBy   = "id";
    private String  sortDir  = "ASC";
    private int     limit    = 25;
    private int     offset   = 0;
    // getters and setters omitted
}
UserMapper.xml
<sql id="searchPredicates">
  <where>
    <if test="nameLike != null and nameLike != ''">
      <bind name="pattern" value="'%' + nameLike + '%'"/>
      AND LOWER(u.user_name) LIKE LOWER(#{pattern}) ESCAPE '!'
    </if>

    <if test="statuses != null and statuses.size() > 0">
      AND u.status IN
      <foreach collection="statuses" item="s" open="(" separator="," close=")">
        #{s}
      </foreach>
    </if>

    <if test="createdFrom != null">AND u.created_at &gt;= #{createdFrom}</if>
    <if test="createdTo   != null">AND u.created_at &lt;  #{createdTo}</if>

    <choose>
      <when test="hasOrders != null and hasOrders">
        AND EXISTS (SELECT 1 FROM customer_order o WHERE o.user_id = u.id)
      </when>
      <when test="hasOrders != null and !hasOrders">
        AND NOT EXISTS (SELECT 1 FROM customer_order o WHERE o.user_id = u.id)
      </when>
    </choose>
  </where>
</sql>

<select id="search" resultType="User">
  SELECT u.id, u.user_name, u.email, u.status, u.created_at
  FROM app_user u
  <include refid="searchPredicates"/>
  ORDER BY ${sortBy} ${sortDir}
  LIMIT #{limit} OFFSET #{offset}
</select>

<select id="countSearch" resultType="long">
  SELECT COUNT(*)
  FROM app_user u
  <include refid="searchPredicates"/>
</select>
Those two ${} need a whitelist

sortBy and sortDir are interpolated as raw SQL. Validate them in the service before the mapper is ever called — see chapter 4 for the pattern.

Debugging generated SQL

Turn the mapper logger to DEBUG and MyBatis prints the final statement with its parameters. When you need the SQL without executing it, ask the Configuration directly:

SqlPeek.java
Configuration cfg = sqlSessionFactory.getConfiguration();

MappedStatement ms =
        cfg.getMappedStatement("com.bitsnippets.shop.mapper.UserMapper.search");

BoundSql boundSql = ms.getBoundSql(query);

System.out.println(boundSql.getSql());               // the assembled statement
System.out.println(boundSql.getParameterMappings()); // the ? bindings, in order

Which snippet produces valid SQL when every filter is null?

<where> emits nothing at all when its body is empty, so the statement stays valid. A bare WHERE keyword followed by nothing is a syntax error, and <set> belongs to UPDATE, not SELECT.