Chapter 05

Annotation-based mappers

Anything you can express in mapper XML you can also express with annotations. Whether you should depends entirely on how long the SQL is — and this chapter gives you a concrete threshold instead of a taste preference.

⏱ 14 min readLevel: beginner → intermediate

The four statement annotations

No XML file, no namespace, no <mappers> entry beyond registering the interface itself. Under Spring Boot, @Mapper plus component scanning is enough.

ProductMapper.java
package com.bitsnippets.shop.mapper;

import com.bitsnippets.shop.domain.Product;
import org.apache.ibatis.annotations.*;

import java.math.BigDecimal;
import java.util.List;

@Mapper
public interface ProductMapper {

    @Select("SELECT id, sku, name, price FROM product WHERE id = #{id}")
    Product findById(Long id);

    @Select("SELECT id, sku, name, price FROM product ORDER BY name")
    List<Product> findAll();

    @Insert("""
            INSERT INTO product (sku, name, price)
            VALUES (#{sku}, #{name}, #{price})
            """)
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    int insert(Product product);

    @Update("UPDATE product SET price = #{price} WHERE id = #{id}")
    int updatePrice(@Param("id") Long id, @Param("price") BigDecimal price);

    @Delete("DELETE FROM product WHERE id = #{id}")
    int deleteById(Long id);
}
Text blocks changed the calculus

Before Java 15, multi-line SQL in an annotation meant an array of concatenated strings and a permanent risk of a missing space at a line break. With text blocks (""") annotation SQL is genuinely readable, which is why annotation mappers are far more common in modern codebases than they were in 2015.

@Param and parameter binding

Same rules as XML: one argument exposes its properties directly, several arguments need names. Compiling with -parameters lets MyBatis use the real names, but @Param is explicit and survives obfuscation — use it.

ProductMapper.java
// single POJO: #{sku}, #{price} resolve against the object
@Select("SELECT * FROM product WHERE sku = #{sku} AND price <= #{price}")
List<Product> findCheaperThan(Product probe);

// several scalars: name them
@Select("SELECT * FROM product WHERE price BETWEEN #{min} AND #{max}")
List<Product> findInRange(@Param("min") BigDecimal min,
                          @Param("max") BigDecimal max);

// collection parameter — see @SelectProvider or XML foreach for the IN clause
@Select("<script>" +
        "SELECT * FROM product WHERE id IN " +
        "<foreach item='id' collection='ids' open='(' separator=',' close=')'>#{id}</foreach>" +
        "</script>")
List<Product> findByIds(@Param("ids") List<Long> ids);

@Results and @Result

The annotation equivalent of <resultMap>. Give it an id and other methods can reuse it via @ResultMap.

UserMapper.java
@Results(id = "userResult", value = {
    @Result(property = "id",        column = "id", id = true),
    @Result(property = "userName",  column = "user_name"),
    @Result(property = "email",     column = "email"),
    @Result(property = "status",    column = "status",
            typeHandler = UserStatusTypeHandler.class),
    @Result(property = "createdAt", column = "created_at")
})
@Select("SELECT id, user_name, email, status, created_at FROM app_user WHERE id = #{id}")
User findById(Long id);

// reuse the map declared above — no duplication
@ResultMap("userResult")
@Select("SELECT id, user_name, email, status, created_at FROM app_user ORDER BY id")
List<User> findAll();

Associations and collections

Nested mapping works, but only in the nested select style — which means one extra query per parent row unless you enable lazy loading. For nested results (a single join mapped into a graph) XML remains clearer, as chapter 8 shows.

UserMapper.java
@Results(id = "userWithOrders", value = {
    @Result(property = "id",       column = "id", id = true),
    @Result(property = "userName", column = "user_name"),
    @Result(property = "address",  column = "id",
            one = @One(select = "com.bitsnippets.shop.mapper.AddressMapper.findByUserId",
                       fetchType = FetchType.LAZY)),
    @Result(property = "orders",   column = "id",
            many = @Many(select = "com.bitsnippets.shop.mapper.OrderMapper.findByUserId",
                         fetchType = FetchType.LAZY))
})
@Select("SELECT id, user_name FROM app_user WHERE id = #{id}")
User findWithOrders(Long id);
This is an N+1 generator

Call findWithOrders in a loop over 500 users and you issue 1001 queries. Use it for single-aggregate loads only; for lists, write a join with a nested <collection> result map.

@Options

AttributeEquivalent XML attributeTypical use
useGeneratedKeys, keyProperty, keyColumnsameIdentity-column inserts
flushCacheflushCacheForce a fresh read
useCacheuseCacheSkip the second level cache
timeouttimeoutPer-statement timeout
fetchSizefetchSizeLarge result streaming
statementTypestatementTypeCALLABLE for stored procedures
resultSetTyperesultSetTypeScrollable cursors

@SelectKey for sequences

OrderMapper.java
@Insert("""
        INSERT INTO customer_order (id, user_id, total, status)
        VALUES (#{id}, #{userId}, #{total}, #{status})
        """)
@SelectKey(statement = "SELECT customer_order_seq.NEXTVAL FROM dual",
           keyProperty = "id",
           resultType = Long.class,
           before = true)
int insert(Order order);

before = true runs the key query first so the value can be used in the insert. Use before = false for databases where the key is only available afterwards, such as SELECT LAST_INSERT_ID() on MySQL — though @Options with useGeneratedKeys is simpler there.

SQL providers: dynamic SQL in Java

When the SQL must be built conditionally, you have two options. Embedding <script> tags inside a string works but is unpleasant. Providers move the construction into a real Java class where the compiler can help.

ProductMapper.java
@SelectProvider(type = ProductSqlProvider.class, method = "search")
List<Product> search(ProductQuery query);
ProductSqlProvider.java
package com.bitsnippets.shop.mapper;

import org.apache.ibatis.jdbc.SQL;

public class ProductSqlProvider {

    public String search(ProductQuery query) {
        return new SQL() {{
            SELECT("id", "sku", "name", "price");
            FROM("product");

            if (query.getNameLike() != null) {
                WHERE("name LIKE #{nameLike}");
            }
            if (query.getMinPrice() != null) {
                WHERE("price >= #{minPrice}");
            }
            if (query.getMaxPrice() != null) {
                WHERE("price <= #{maxPrice}");
            }
            ORDER_BY("name ASC");
        }}.toString();
    }
}

The SQL builder handles the tedious parts: it inserts WHERE only if there is at least one condition, joins conditions with AND, and formats the output readably. There are matching @InsertProvider, @UpdateProvider and @DeleteProvider annotations.

Double-brace initialisation

The new SQL() {{ … }} idiom creates an anonymous subclass. It reads beautifully but holds a reference to the enclosing instance and defeats some serialisation. If that bothers you, build the object with ordinary method calls instead — the API is identical.

Mixing XML and annotations

One interface can use both, as long as no statement is defined twice. A common and very workable split:

  • Annotations for short, static statements: lookups by id, counts, simple deletes.
  • XML for anything with dynamic branches, joins, or more than about eight lines of SQL.
UserMapper.java — hybrid
@Mapper
public interface UserMapper {

    @Select("SELECT COUNT(*) FROM app_user WHERE status = 'ACTIVE'")
    long countActive();

    @Delete("DELETE FROM app_user WHERE id = #{id}")
    int deleteById(Long id);

    // no annotation: MyBatis looks for <select id="search"> in UserMapper.xml
    List<User> search(UserQuery query);

    List<User> findWithOrders(@Param("ids") List<Long> ids);
}
Defining the same id twice

If search exists as both @Select and an XML statement, startup fails with “Mapped Statements collection already contains value for …”. The error is clear; the ten minutes you spend finding the duplicate are not.

XML or annotations: a decision table

SituationChooseWhy
One-line query on a primary keyAnnotationThe method and its SQL stay on one screen
Statement longer than ~10 linesXMLAnnotations stop being readable and diffs get ugly
Three or more dynamic branchesXMLThe <where>/<if> engine beats string building
Nested result mapping from a joinXMLNested <collection> is far clearer than nested @Result
SQL reviewed by DBAsXMLThey can read it without opening an IDE
Vendor-specific variantsXMLdatabaseId is XML-only
Tiny microservice, 6 statementsAnnotationOne file instead of three
Team already has 200 XML mappersXMLConsistency is worth more than the marginal win

You need a search with five optional filters, a join to orders, and a total row count. Which do you reach for?

Five optional filters plus nested mapping is exactly the case the XML dynamic engine was designed for. String concatenation in the service layer is the one answer that is not just unpleasant but actively dangerous — it reopens the SQL injection door.