Chapter 04

Mapper XML in depth

The mapper file is where MyBatis actually lives. There are only nine top-level elements, and you will use five of them every day.

⏱ 18 min readLevel: beginner → intermediateCore chapter

The nine elements

ElementPurposeCovered in
<select>Read data and map it to objectsthis chapter
<insert>Write a row, optionally returning generated keysthis chapter + ch. 6
<update>Modify rows, returns affected countthis chapter
<delete>Remove rows, returns affected countthis chapter
<sql>Reusable SQL fragmentthis chapter
<resultMap>Explicit column-to-property mappingch. 8
<cache>Enable the namespace cachech. 9
<cache-ref>Share another namespace's cachech. 9
<parameterMap>Legacy parameter mappingdeprecated — do not use

Namespace: the one rule that binds everything

The namespace attribute must be the fully qualified name of the mapper interface. MyBatis concatenates namespace and statement id to form a unique statement id such as com.bitsnippets.shop.mapper.UserMapper.findById, and that string is what the interface proxy looks up.

Invalid bound statement (not found)

Ninety percent of the time this exception means one of four things: the XML is not on the runtime classpath, the namespace does not match the interface, the statement id does not match the method name, or two mappers share a namespace. Check them in that order.

select

UserMapper.xml
<select id="findById"
        parameterType="long"
        resultType="User"
        useCache="true"
        flushCache="false"
        timeout="10"
        fetchSize="100"
        statementType="PREPARED"
        resultSetType="FORWARD_ONLY">
  SELECT id, user_name, email, status, created_at, version
  FROM app_user
  WHERE id = #{id}
</select>
AttributeDefaultNotes
idrequiredMust match the interface method name.
parameterTypeinferredAlmost always redundant — MyBatis works it out. Omit it.
resultType—Mutually exclusive with resultMap.
resultMap—Reference to a <resultMap id>. Needed for joins and nesting.
useCachetrueWhether results go into the second level cache.
flushCachefalse for selectSet true on a select that must always hit the database.
timeoutfrom settingsSeconds before the driver is asked to cancel.
fetchSizedriver defaultRows per network round trip. Matters for large exports.
statementTypePREPAREDSTATEMENT, PREPARED, CALLABLE. Never use STATEMENT with user input.
resultSetTypedriver defaultFORWARD_ONLY, SCROLL_INSENSITIVE, SCROLL_SENSITIVE, DEFAULT.
resultOrderedfalseWith nested maps, promises rows are grouped — allows streaming without buffering.

Return types the interface may declare

UserMapper.java
public interface UserMapper {

    User            findById(Long id);          // 0 or 1 row; >1 row throws TooManyResultsException
    Optional<User>  findByEmail(String email);  // supported since 3.5.0
    List<User>      findAll();
    Set<User>       findDistinct();
    User[]          findArray();
    long            countActive();              // single scalar column
    Map<String, Object> findRawById(Long id);   // column name -> value

    @MapKey("id")                               // List becomes a Map keyed by a property
    Map<Long, User> findAllIndexed();

    Cursor<User>    streamAll();                // lazy, one row at a time
    void            findAll(ResultHandler<User> handler);   // callback style
}
Streaming millions of rows

A Cursor<T> plus fetchSize lets you walk a huge result set without loading it into memory. The cursor is only valid while the session is open, so consume it inside the try-with-resources block — and on PostgreSQL, remember that server-side cursors require autocommit to be off.

ExportJob.java
try (SqlSession session = factory.openSession();
     Cursor<User> cursor = session.getMapper(UserMapper.class).streamAll()) {

    for (User user : cursor) {
        writer.write(toCsv(user));
    }
}

insert

UserMapper.xml
<!-- databases with identity columns: MySQL, PostgreSQL serial, H2, SQL Server -->
<insert id="insert" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
  INSERT INTO app_user (user_name, email, status)
  VALUES (#{userName}, #{email}, #{status})
</insert>

<!-- sequence databases: Oracle, or PostgreSQL when you want the id before insert -->
<insert id="insertWithSequence">
  <selectKey keyProperty="id" resultType="long" order="BEFORE">
    SELECT app_user_seq.NEXTVAL FROM dual
  </selectKey>
  INSERT INTO app_user (id, user_name, email, status)
  VALUES (#{id}, #{userName}, #{email}, #{status})
</insert>

Both forms mutate the object you passed in: after the call, user.getId() returns the new key. The method's own return value is the affected row count, not the id — a detail that trips up nearly everyone once.

update and delete

UserMapper.xml
<update id="updateEmail">
  UPDATE app_user
  SET email = #{email},
      version = version + 1
  WHERE id = #{id}
    AND version = #{version}
</update>

<delete id="deleteById">
  DELETE FROM app_user WHERE id = #{id}
</delete>

<!-- soft delete: usually a better idea -->
<update id="deactivate">
  UPDATE app_user SET status = 'DELETED' WHERE id = #{id}
</update>

Both return int — the number of affected rows. Use it: a zero from updateEmail above means either the row is gone or someone else updated it first, which is exactly how optimistic locking is detected (chapter 6).

#{} versus ${} — read this twice

This is the single most important thing in the chapter, because getting it wrong is a security vulnerability rather than a bug.

Safe

#{property}

Becomes a JDBC ? placeholder. The value is bound by a type handler and can never change the structure of the statement.

-- source
WHERE user_name = #{name}
-- sent to the driver
WHERE user_name = ?      -- name bound as a String
Dangerous

${property}

Raw string substitution before parsing. Whatever the value contains becomes SQL.

-- source
WHERE user_name = '${name}'
-- with name = x' OR '1'='1
WHERE user_name = 'x' OR '1'='1'
Rule

Use #{} for every value. Use ${} only for identifiers — table names, column names, sort direction — and only when the value comes from a whitelist you control in Java, never straight from a request parameter.

the correct way to do dynamic sorting
private static final Set<String> SORTABLE =
        Set.of("id", "user_name", "email", "created_at");

public List<User> findSorted(String column, String direction) {
    if (!SORTABLE.contains(column)) {
        throw new IllegalArgumentException("Unsortable column: " + column);
    }
    String dir = "DESC".equalsIgnoreCase(direction) ? "DESC" : "ASC";
    return userMapper.findSorted(column, dir);   // now ${} is safe
}
UserMapper.xml
<select id="findSorted" resultType="User">
  SELECT id, user_name, email FROM app_user
  ORDER BY ${column} ${direction}
</select>

Extra parameter metadata

The full #{} syntax carries optional metadata, most of which you will only need for nulls, decimals and stored procedures:

parameter syntax
#{property}
#{property,jdbcType=VARCHAR}
#{amount,javaType=java.math.BigDecimal,jdbcType=DECIMAL,numericScale=2}
#{metadata,typeHandler=com.bitsnippets.shop.handler.JsonTypeHandler}
#{outParam,mode=OUT,jdbcType=CURSOR,resultMap=userMap}

jdbcType is required when a parameter can be null and your driver cannot infer the type — Oracle is the usual offender, throwing “Invalid column type” without it.

Reusable fragments: sql and include

Column lists get repeated across five or six statements. A fragment keeps them in one place, and fragments can take parameters through <property>.

UserMapper.xml
<sql id="userColumns">
  ${alias}.id, ${alias}.user_name, ${alias}.email,
  ${alias}.status, ${alias}.created_at, ${alias}.version
</sql>

<sql id="activeOnly">
  AND ${alias}.status = 'ACTIVE'
</sql>

<select id="findById" resultType="User">
  SELECT <include refid="userColumns"><property name="alias" value="u"/></include>
  FROM app_user u
  WHERE u.id = #{id}
</select>

<select id="findActiveWithOrders" resultMap="userWithOrders">
  SELECT <include refid="userColumns"><property name="alias" value="u"/></include>,
         o.id AS o_id, o.total AS o_total
  FROM app_user u
  LEFT JOIN customer_order o ON o.user_id = u.id
  WHERE 1 = 1
  <include refid="activeOnly"><property name="alias" value="u"/></include>
</select>

Fragments can also be pulled from another namespace by qualifying the id — handy for a shared CommonMapper.xml holding audit columns or tenant predicates:

cross-namespace include
<include refid="com.bitsnippets.shop.mapper.CommonMapper.auditColumns"/>

Escaping XML in SQL

< and & are XML metacharacters. Two ways to survive them:

UserMapper.xml
<!-- 1. entity references -->
<select id="createdBefore" resultType="User">
  SELECT * FROM app_user WHERE created_at &lt; #{cutoff}
</select>

<!-- 2. CDATA — better when there are several operators -->
<select id="inRange" resultType="User">
  SELECT * FROM app_user
  <![CDATA[
    WHERE created_at >= #{from}
      AND created_at <  #{to}
      AND version    <> 0
  ]]>
</select>
CDATA hides dynamic tags

Anything inside <![CDATA[ … ]]> is literal text, so an <if> placed inside it will be sent to the database verbatim. Wrap only the comparison, not the whole statement.

Multiple parameters

A single-argument method exposes that object's properties directly. With two or more arguments you must name them, or MyBatis falls back to arg0/param1 positional names that nobody enjoys reading.

UserMapper.java
List<User> search(@Param("status") String status,
                  @Param("since")  LocalDateTime since);
UserMapper.xml
<select id="search" resultType="User">
  SELECT id, user_name, email FROM app_user
  WHERE status = #{status}
    AND created_at &gt;= #{since}
</select>

Chapter checklist

  • Namespace equals the interface FQN; statement ids equal method names.
  • #{} for values, ${} for whitelisted identifiers only.
  • Drop parameterType — it adds noise and no value.
  • Extract column lists into <sql> fragments as soon as they repeat.
  • Use the returned row count from updates and deletes; never ignore it.
  • Prefer CDATA over a wall of &lt; entities, but keep dynamic tags outside it.

Which of these is a legitimate use of ${}?

Values always go through #{}. Identifiers — column names, table names, sort direction — cannot be bound as JDBC parameters, so ${} is the only option, which is precisely why the value must be validated in Java first.