Skip to main content

MyBatis with Spring Boot 4: Mappers, Dynamic SQL and Pagination

A first-meeting guide to MyBatis on Spring Boot 4.2: annotation and XML mappers, result maps (JOIN vs N+1), dynamic SQL, #{} vs ${}, PageHelper and its ThreadLocal trap, and @MybatisTest. Every SQL statement quoted was printed by a real run of the companion module.

If you have used Spring Data JPA, you have met the moment when a query gets too clever for derived method names, and you end up writing JPQL, then native SQL, then fighting the persistence context to get a result back in the shape you wanted. MyBatis starts from the opposite end: you write the SQL, always, and the library does the boring parts — binding parameters, running the statement, and turning rows into objects. No entity lifecycle, no dirty checking, no lazy loading surprises. What you see in the SQL is what runs. This post is a first meeting with MyBatis on Spring Boot 4. It assumes you know Java and basic SQL, and nothing about MyBatis. It goes in the order a newcomer needs: set it up, write a mapper with annotations, move to XML when the SQL grows, build queries whose shape depends on the input (dynamic SQL), page the results, and test it all with @MybatisTest. Every SQL statement and number quoted below was printed by MyBatis itself during a real run of the companion module, and each block links to the file it came from.
Versions, all verified against Maven Central metadata and a real run. Spring Boot 4.2.0 (GA on 19 November 2026, the newest GA when this was written), Spring Framework 7.1.0, mybatis-spring-boot-starter 4.1.0 (MyBatis 3.5.19, MyBatis-Spring 4.1.0), pagehelper-spring-boot-starter 4.1.1 (PageHelper 6.1.1), H2 2.5.252, JDK 25 (Temurin 25.0.5, the current LTS). The MyBatis starter line is the one that supports Boot 4: its 4.1.0 build declares Boot 4.1.0, and it ran unchanged on 4.2.0 here (the jar names are printed in 06-versions-and-full-context.txt). MyBatis starter 3.x belongs to Boot 3.

MyBatis in one picture: you write the SQL, it does the plumbing

Before any code, here is the whole mental model. A mapper is a Java interface. Each method on it is tied to one SQL statement, either written in an annotation above the method or in an XML file. When your service calls the method, MyBatis takes the arguments, puts them into the statement as ? bind parameters, runs it through plain JDBC, and converts the rows that come back into the Java type the method returns.
your servicemapper.findById(7)mapper interfaceProductMappermapped statementSQL text, #{id}JDBCPreparedStatementid = ? [7]result mappingrow -> ProductYou write the interface and the SQL. MyBatis binds each #{name} as a ? parameter, runs the statement,and turns each row into an object. It never writes the SQL for you, and that is the whole idea.
The sentence under the diagram is the point worth keeping: MyBatis is not trying to hide SQL. That makes it a good fit when the SQL matters (reports, joins across legacy tables, database-specific features) and a worse fit when you mostly want to save, load and forget. We come back to that at the end.
Intermediate: where MyBatis sits next to JPA and JdbcClient

JPA maps whole object graphs and generates SQL for you. JdbcClient (covered in JdbcClient in Spring Framework 7) is plain JDBC with a friendlier API and leaves mapping to row mappers you write. MyBatis sits between: you still write every statement, but the mapping from columns to object fields is declarative (annotations, or XML result maps), and the library gives you dynamic SQL tags so you do not build query strings with StringBuilder.

The connection and transaction handling are Spring’s. MyBatis-Spring takes connections from the Spring-managed DataSource, so @Transactional works the way it does for any JDBC code.

Going deeper

Setting it up takes one dependency and one setting you will want

The starter brings MyBatis, the Spring integration and the auto-configuration. The demo also adds the PageHelper starter (used in the pagination section), H2 as an in-memory database, and the MyBatis test starter. The dependency block, from pom.xml:
<dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>${mybatis-starter.version}</version>
    </dependency>
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper-spring-boot-starter</artifactId>
      <version>${pagehelper-starter.version}</version>
    </dependency>
Neither starter is managed by the Spring Boot BOM, so the versions are explicit properties in the pom (4.1.0 and 4.1.1). That is a real cost of MyBatis on Boot: you pick the starter version that matches your Boot line yourself. The configuration, from application.properties:
# MyBatis
mybatis.mapper-locations=classpath:mappers/*.xml
mybatis.type-aliases-package=com.ankurm.mybatis.model
mybatis.configuration.map-underscore-to-camel-case=true
# Prints "==> Preparing: ..." and "==> Parameters: ..." for every statement
logging.level.com.ankurm.mybatis.mapper=DEBUG

# PageHelper
pagehelper.helper-dialect=h2
pagehelper.reasonable=false
Three of those lines matter on day one. mapper-locations says where the XML mapper files live. type-aliases-package lets the XML say type="Product" instead of the full class name. And map-underscore-to-camel-case is the one that bites: databases name columns category_id, Java names fields categoryId, and MyBatis does not connect them unless you ask. The mapper interfaces need no registration at all: annotating them with @Mapper is enough, the starter scans for it.
The silent null. With map-underscore-to-camel-case=false (MyBatis’s own default) nothing fails. The query runs, the row comes back, and the field simply stays null:

Output, from output/07-camel-case.txt:
## mybatis.configuration.map-underscore-to-camel-case=false  (MyBatis's own default)
columns in the SELECT: id, name, price, stock, active, category_id
result: Product[7, Product 07, 27.50, stock=9, active=true, categoryId=null]

Nothing in the log tells you a column was dropped. If one property of an otherwise fine object is mysteriously null, check the naming rule first.
Intermediate: what the SQL logging lines mean and how this transcript was made

The logging.level.com.ankurm.mybatis.mapper=DEBUG line is what prints every statement. MyBatis logs under the name of the mapper method, so turning on DEBUG for your mapper package gives you ==> Preparing: (the SQL with ? placeholders), ==> Parameters: (the bound values with their Java types) and <== Total: or <== Updates: (rows returned or changed). Every transcript below is made of exactly those lines.

The test helpers capture them with a logback list appender, so what you read is what the logger emitted, not a retyped copy: see SqlLog.java and Transcript.java. Because the tests assert the same facts they print, a transcript cannot drift from the code without the build failing.

Going deeper

Your first mapper: SQL in annotations

For short, fixed statements the annotation style is the quickest. The interface below has a select by id, a select of all rows, a three-column projection into a Java record, an insert that writes the generated key back, a guarded update and a delete. The first few methods, from ProductMapper.java:
    @Select("SELECT id, name, price, stock, active, category_id FROM product WHERE id = #{id}")
    Optional<Product> findById(long id);

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

    /** Selects three columns into a record. */
    @Select("SELECT id, name, price FROM product WHERE active = TRUE ORDER BY price DESC LIMIT #{limit}")
    List<ProductSummary> topPriced(int limit);

    @Insert("INSERT INTO product(name, price, stock, active, category_id) "
            + "VALUES (#{name}, #{price}, #{stock}, #{active}, #{categoryId})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Product product);
Running them prints this. Read the Preparing line against the annotation above: #{id} became ?, and the value travels separately on the Parameters line. A missing row comes back as Optional.empty because the method says it returns an Optional; there is no exception to catch. Output, from output/01-annotation-mapper.txt:
## findById(7)
==>  Preparing: SELECT id, name, price, stock, active, category_id FROM product WHERE id = ?
==> Parameters: 7(Long)
<==      Total: 1
result: Product[7, Product 07, 27.50, stock=9, active=true, categoryId=2]

## findById(999)  (no such row, returns Optional)
==>  Preparing: SELECT id, name, price, stock, active, category_id FROM product WHERE id = ?
==> Parameters: 999(Long)
<==      Total: 0
result: Optional.empty

## topPriced(3)  -> List<ProductSummary> (a record)
==>  Preparing: SELECT id, name, price FROM product WHERE active = TRUE ORDER BY price DESC LIMIT ?
==> Parameters: 3(Integer)
<==      Total: 3
  ProductSummary[id=45, name=Product 45, price=122.50]
  ProductSummary[id=44, name=Product 44, price=120.00]
  ProductSummary[id=43, name=Product 43, price=117.50]

## insert  (id before: null)
==>  Preparing: INSERT INTO product(name, price, stock, active, category_id) VALUES (?, ?, ?, ?, ?)
==> Parameters: Desk lamp(String), 39.90(BigDecimal), 12(Integer), true(Boolean), 2(Long)
<==    Updates: 1
rows affected: 1
id after (written back by useGeneratedKeys): 46
Two things in that output reward a second look. The projection printed ProductSummary[id=45, ...]: a Java record works as a result type, MyBatis finds the canonical constructor and matches columns to its parameters by name. And the insert went in with id before: null and came out with 46, because @Options(useGeneratedKeys = true, keyProperty = "id") asks the driver for the generated key and writes it into the object you passed.
A guard in the WHERE clause is the simplest concurrency check. decrementStock is UPDATE ... SET stock = stock - ? WHERE id = ? AND stock >= ?. The return value is the number of rows changed, so 0 means “not enough stock” with no exception and no read-then-write race:

Output, from output/01-annotation-mapper.txt:
## decrementStock(id=1, qty=3)  (stock of product 1 is 7)
==>  Preparing: UPDATE product SET stock = stock - ? WHERE id = ? AND stock >= ?
==> Parameters: 3(Integer), 1(Long), 3(Integer)
<==    Updates: 1
rows affected: 1

## decrementStock(id=1, qty=500)  (guard in WHERE: stock >= qty)
==>  Preparing: UPDATE product SET stock = stock - ? WHERE id = ? AND stock >= ?
==> Parameters: 500(Integer), 1(Long), 500(Integer)
<==    Updates: 0
rows affected: 0
Intermediate: naming columns yourself with @Results, and what you get without it

When column names do not match field names, annotation mappers can spell the mapping out with @Results. The same query is declared twice in the demo, once with the mapping and once without, with the columns aliased to label and cost:

    @Select("SELECT id AS pid, name AS label, price AS cost FROM product WHERE id = #{id}")
    @Results(id = "renamed", value = {
            @Result(column = "pid", property = "id", id = true),
            @Result(column = "label", property = "name"),
            @Result(column = "cost", property = "price")
    })
    Product findWithRenamedColumns(long id);

Output, from output/01-annotation-mapper.txt:

## columns aliased to label / cost (id keeps its name)
with @Results:    Product[7, Product 07, 27.50, stock=null, active=null, categoryId=null]
without @Results: Product[7, null, null, stock=null, active=null, categoryId=null]

Without the mapping, only id (whose name already matched) arrived. Same silent-null family as the camel-case setting: MyBatis maps what it can match by name and leaves the rest alone.

Every test in that class runs in a transaction that is rolled back. The transcript shows it: after delete(1) the row is gone inside the test, and a later test sees all 45 rows again.

## delete(1)
==>  Preparing: DELETE FROM product WHERE id = ?
==> Parameters: 1(Long)
<==    Updates: 1
rows affected: 1
findById(1) inside the same test transaction: Optional.empty

## a later test sees the original data again (rollback)
findAll().size() = 45, findById(1) present = true

Going deeper

When the SQL grows, move it to XML and describe the mapping once

Annotations get cramped quickly: a multi-line join inside a Java string, no syntax highlighting, no way to reuse a column list. The XML style keeps the interface almost empty and moves the SQL to a file that MyBatis matches by namespace (the interface’s full name) and statement id (the method name). The interface is just signatures, from ProductXmlMapper.java:
    List<Product> search(@Param("f") ProductFilter filter);

    /** Joins the category and maps it into {@code product.category} through an association. */
    Product findWithCategory(long id);
The statement behind findWithCategory is a join, and it needs something annotations did not: a result map. A result map says which column fills which property, and, with an <association>, that a few of the columns belong to a nested object. From ProductXmlMapper.xml:
  <!-- Result map: product columns, plus the joined category as a nested object (association). -->
  <resultMap id="productWithCategoryMap" type="Product">
    <id     column="id"          property="id"/>
    <result column="name"        property="name"/>
    <result column="price"       property="price"/>
    <result column="stock"       property="stock"/>
    <result column="active"      property="active"/>
    <result column="category_id" property="categoryId"/>
    <association property="category" javaType="Category">
      <id     column="c_id"   property="id"/>
      <result column="c_name" property="name"/>
    </association>
  </resultMap>

  <select id="findWithCategory" resultMap="productWithCategoryMap">
    SELECT <include refid="productColumns"/>, c.id AS c_id, c.name AS c_name
    FROM product p JOIN category c ON c.id = p.category_id
    WHERE p.id = #{id}
  </select>
The columns c_id and c_name are aliases in the SELECT so the two id columns do not collide. The result is a Product with its category filled in, from one statement: Output, from output/02-result-maps.txt:
## findWithCategory(7)  -> association fills product.category from joined columns
==>  Preparing: SELECT p.id, p.name, p.price, p.stock, p.active, p.category_id , c.id AS c_id, c.name AS c_name FROM product p JOIN category c ON c.id = p.category_id WHERE p.id = ?
==> Parameters: 7(Long)
<==      Total: 1
result: Product[7, Product 07, 27.50, stock=9, active=true, categoryId=2, category=Gadgets]
The same idea scales to one-to-many with <collection>, and there are two ways to load it. That choice decides how many statements you run:
JOIN + nested result map1 statement41 rows folded into 3 Category objectsallWithProductsJoin()SELECT id, name FROM categorycategory_id = 1 (14 rows)category_id = 2 (13 rows)category_id = 3 (14 rows)nested select: 1 + 3 = 4 statementsBoth return the same products per category (02-result-maps.txt). The left one costs one round trip, the right one costs one per category.With 3 categories the difference is invisible. With 3,000 it is the N+1 problem, and MyBatis will not warn you.
In the JOIN version one query returns 41 rows (one per active product) and MyBatis folds them into 3 Category objects, using the <id> element to know which rows belong to the same category. In the nested-select version the collection names a second statement and a column to pass to it, and MyBatis runs it once per category. Here is the measured difference: Output, from output/02-result-maps.txt:
## allWithProductsJoin()  -> one statement, nested result map folds rows into objects
==>  Preparing: SELECT c.id AS c_id, c.name AS c_name, p.id AS p_id, p.name AS p_name, p.price AS p_price, p.stock AS p_stock FROM category c LEFT JOIN product p ON p.category_id = c.id AND p.active = TRUE ORDER BY c.id, p.id
==> Parameters: 
<==      Total: 41
  Category[1, Books, products=14]
  Category[2, Gadgets, products=13]
  Category[3, Kitchen, products=14]
statements executed: 1

## allWithProductsNestedSelect()  -> one query, then one more per category
==>  Preparing: SELECT id, name FROM category ORDER BY id
==> Parameters: 
====>  Preparing: SELECT id, name, price, stock, active, category_id FROM product WHERE category_id = ? AND active = TRUE ORDER BY id
====> Parameters: 1(Long)
<====      Total: 14
====>  Preparing: SELECT id, name, price, stock, active, category_id FROM product WHERE category_id = ? AND active = TRUE ORDER BY id
====> Parameters: 2(Long)
<====      Total: 13
====>  Preparing: SELECT id, name, price, stock, active, category_id FROM product WHERE category_id = ? AND active = TRUE ORDER BY id
====> Parameters: 3(Long)
<====      Total: 14
<==      Total: 3
  Category[1, Books, products=14]
  Category[2, Gadgets, products=13]
  Category[3, Kitchen, products=14]
statements executed: 4
The nested select is N+1 in plain sight. statements executed: 4 for 3 categories. It reads nicely in XML and it is correct, which is exactly why it ships to production: one statement per parent row, and the count grows with your data. Prefer the JOIN and a nested result map for lists; keep nested selects for a single object, or for data you only sometimes need (MyBatis can load those lazily, see the reference below). If you work with Hibernate too, the same trap and a way to catch it automatically is in Catch N+1 Queries Automatically in Hibernate 7.
Intermediate: the two collection result maps side by side

The JOIN version, with the nested <collection> using prefixed aliases (p_id, p_name) so product columns do not clash with category columns. From CategoryMapper.xml:

  <resultMap id="categoryJoinMap" type="Category">
    <id     column="c_id"   property="id"/>
    <result column="c_name" property="name"/>
    <collection property="products" ofType="Product">
      <id     column="p_id"    property="id"/>
      <result column="p_name"  property="name"/>
      <result column="p_price" property="price"/>
      <result column="p_stock" property="stock"/>
    </collection>
  </resultMap>

  <select id="allWithProductsJoin" resultMap="categoryJoinMap">
    SELECT c.id AS c_id, c.name AS c_name, p.id AS p_id, p.name AS p_name, p.price AS p_price, p.stock AS p_stock
    FROM category c LEFT JOIN product p ON p.category_id = c.id AND p.active = TRUE
    ORDER BY c.id, p.id
  </select>

The nested-select version. The select attribute names another statement, column says which column of the outer row becomes its #{id} parameter:

  <resultMap id="categoryNestedSelectMap" type="Category">
    <id     column="id"   property="id"/>
    <result column="name" property="name"/>
    <collection property="products" ofType="Product" column="id" select="productsOfCategory"/>
  </resultMap>

  <select id="productsOfCategory" resultType="Product">
    SELECT id, name, price, stock, active, category_id FROM product WHERE category_id = #{id} AND active = TRUE ORDER BY id
  </select>

One detail in the JOIN query is easy to miss: the product filter (p.active = TRUE) is in the LEFT JOIN ... ON, not in a WHERE. In a WHERE it would drop categories that have no active products; in the ON clause they stay, with an empty list. The test also checks that both strategies return the same product ids per category.

Going deeper

Dynamic SQL: one statement that changes shape with its input

A search screen has five optional filters. Written naively that is thirty-two possible queries, or a method that glues strings together and gets the ANDs wrong. MyBatis dynamic SQL lets you write one statement and decide, per call, which fragments to include. The search statement of the demo, from ProductXmlMapper.xml:
  <!-- Dynamic SQL: <where> adds WHERE/AND only when at least one <if> fires. -->
  <select id="search" resultType="Product">
    SELECT <include refid="productColumns"/> FROM product p
    <where>
      <if test="f.nameContains != null and f.nameContains != ''">
        <bind name="namePattern" value="'%' + f.nameContains + '%'"/>
        AND p.name LIKE #{namePattern}
      </if>
      <if test="f.minPrice != null">AND p.price &gt;= #{f.minPrice}</if>
      <if test="f.maxPrice != null">AND p.price &lt;= #{f.maxPrice}</if>
      <if test="f.active != null">AND p.active = #{f.active}</if>
      <if test="f.categoryIds != null and !f.categoryIds.isEmpty()">
        AND p.category_id IN
        <foreach collection="f.categoryIds" item="cid" open="(" separator="," close=")">#{cid}</foreach>
      </if>
    </where>
    <choose>
      <when test="f.sort == 'price_desc'">ORDER BY p.price DESC, p.id</when>
      <when test="f.sort == 'name'">ORDER BY p.name, p.id</when>
      <otherwise>ORDER BY p.id</otherwise>
    </choose>
  </select>
Read the tags as small decisions. <if test="..."> includes its content only when the OGNL expression is true. <where> adds the word WHERE only if something inside produced text, and strips a leading AND, so every fragment can start with AND without you tracking which one is first. <foreach> expands a list into (?,?,?). <choose> is a switch for the ORDER BY. <bind> builds the %1% LIKE pattern in the XML so the caller passes a plain string. Here is what MyBatis actually sent to the database for four different inputs: Output, from output/03-dynamic-sql.txt:
## no filters: <where> disappears completely
==>  Preparing: SELECT p.id, p.name, p.price, p.stock, p.active, p.category_id FROM product p ORDER BY p.id
==> Parameters: 
<==      Total: 45

## only active = true: <where> appears, no stray AND
==>  Preparing: SELECT p.id, p.name, p.price, p.stock, p.active, p.category_id FROM product p WHERE p.active = ? ORDER BY p.id
==> Parameters: true(Boolean)
<==      Total: 41

## name contains '1', price between 20 and 60
==>  Preparing: SELECT p.id, p.name, p.price, p.stock, p.active, p.category_id FROM product p WHERE p.name LIKE ? AND p.price >= ? AND p.price <= ? ORDER BY p.id
==> Parameters: %1%(String), 20(BigDecimal), 60(BigDecimal)
<==      Total: 10

## categories 1 and 3, sorted by price desc (choose/when)
==>  Preparing: SELECT p.id, p.name, p.price, p.stock, p.active, p.category_id FROM product p WHERE p.category_id IN (?,?) ORDER BY p.price DESC, p.id
==> Parameters: 1(Long), 3(Long)
<==      Total: 30
With no filters the whole WHERE disappears. With one filter there is no stray AND. The category list became IN (?,?) with two bound values. This is the practical win: the Java side just fills a ProductFilter record with whatever the user chose.
#{} and ${} are not the same thing, and one of them is SQL injection. #{name} becomes a ? bind parameter. ${name} is pasted into the SQL text before it is prepared. Same malicious input, two statements; look at the Preparing lines:

Output, from output/03-dynamic-sql.txt:
## ${q}  with q = zzz' OR '1'='1' OR name LIKE '
==>  Preparing: SELECT p.id, p.name, p.price, p.stock, p.active, p.category_id FROM product p WHERE p.name LIKE '%zzz' OR '1'='1' OR name LIKE '%' ORDER BY p.id
==> Parameters: 
<==      Total: 45
rows returned: 45

## #{q}  with q = zzz' OR '1'='1' OR name LIKE '
==>  Preparing: SELECT p.id, p.name, p.price, p.stock, p.active, p.category_id FROM product p WHERE p.name LIKE CONCAT('%', ?, '%') ORDER BY p.id
==> Parameters: zzz' OR '1'='1' OR name LIKE '(String)
<==      Total: 0
rows returned: 0

With ${} the attacker’s quote closed the string and added an OR, so all 45 rows came back. With #{} the same text was an inert parameter and nothing matched. ${} exists for things that cannot be parameters, like a column name in ORDER BY; if you use it for that, pick from a fixed list in Java (the demo’s <choose> does exactly that) and never pass the user’s string through.
Intermediate: set, multi-row insert, and the two ways dynamic SQL produces invalid SQL

Partial updates use <set>, which writes only the columns whose values are not null and removes the trailing comma:

  <!-- <set> strips the trailing comma and fails loudly (SQL error) if nothing is set. -->
  <update id="updateSelective">
    UPDATE product
    <set>
      <if test="name != null">name = #{name},</if>
      <if test="price != null">price = #{price},</if>
      <if test="stock != null">stock = #{stock},</if>
      <if test="active != null">active = #{active},</if>
    </set>
    WHERE id = #{id}
  </update>

Output, from output/03-dynamic-sql.txt. A patch carrying only stock updates only stock:

## updateSelective with only stock set  -> <set> writes just that column
==>  Preparing: UPDATE product SET stock = ? WHERE id = ?
==> Parameters: 99(Integer), 2(Long)
<==    Updates: 1

A multi-row insert is one <foreach> over value tuples, and the generated keys are written back into every object in the list:

## insertAll  -> one INSERT with two value tuples
==>  Preparing: INSERT INTO product(name, price, stock, active, category_id) VALUES (?, ?, ?, ?, ?) , (?, ?, ?, ?, ?)
==> Parameters: A(String), 1.00(BigDecimal), 1(Integer), true(Boolean), 1(Long), B(String), 2.00(BigDecimal), 2(Integer), true(Boolean), 1(Long)
<==    Updates: 2
generated ids written back: [46, 47]

Dynamic SQL is text assembly, so it can assemble broken SQL when a list is empty or no field is set. MyBatis does not guard against that. An empty list into IN, and a patch with nothing to set, both reach the database as syntax errors (the message is H2’s; other databases word it differently):

## findByIds([])  -> foreach over an empty list produces 'IN' with nothing after it
exception: BadSqlGrammarException
root cause: JdbcSQLSyntaxErrorException - Syntax error in SQL statement "SELECT  p.id, p.name, p.price, p.stock, p.active, p.category_id  FROM product p\000a    WHERE p.id IN\000a     \000a    [*]ORDER BY p.id"; expected "("; SQL statement:

## updateSelective with nothing set  -> <set> has no content, the SQL is broken
root cause: JdbcSQLSyntaxErrorException - Syntax error in SQL statement "UPDATE product\000a      \000a    [*]WHERE id = ?"; expected "., AS, SET"; SQL statement:

The search statement avoids the first problem by testing !f.categoryIds.isEmpty() before the foreach; the plain findByIds deliberately does not, to show the failure. Check emptiness in Java before calling, or guard the XML with an <if>.

One more thing you may notice while experimenting: while writing the tests, an identical statement run twice inside one transaction printed its SQL only the first time. MyBatis keeps a per-session first-level cache, so a repeated identical query in the same session can be answered without touching the database. That is why the test for the empty category list sorts by name, to make it a new statement. This was observed during the build; there is no transcript for it, so treat it as a pointer to the MyBatis documentation on localCacheScope rather than a measured result.

Going deeper

Pagination: PageHelper, and the one rule that keeps it safe

MyBatis itself has no page concept. You can write LIMIT ? OFFSET ? by hand, or add the PageHelper plugin, which rewrites your SELECT and runs a matching count query. The starter registers it automatically. Used the safe way, the service is three lines, from ProductService.java:
    public PageInfo<Product> page(ProductFilter filter, int pageNum, int pageSize) {
        return PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> mapper.search(filter));
    }
Asking for page 2 with 10 per page of the unfiltered search produced two statements: a count, and your own SELECT with LIMIT and OFFSET appended. You wrote neither: Output, from output/04-pagination.txt:
## service.page(none, pageNum=2, pageSize=10)  -> PageHelper rewrote the query and added a count query
==>  Preparing: SELECT count(0) FROM product p
==> Parameters: 
<==      Total: 1
==>  Preparing: SELECT p.id, p.name, p.price, p.stock, p.active, p.category_id FROM product p ORDER BY p.id LIMIT ? OFFSET ?
==> Parameters: 10(Integer), 10(Long)
<==      Total: 10
pageNum=2 pageSize=10 size=10 total=45 pages=5
hasPreviousPage=true hasNextPage=true
ids on this page: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

## filter + sort + page: the dynamic SQL and the paging compose
==>  Preparing: SELECT count(0) FROM product p WHERE p.active = ? AND p.category_id IN (?)
==> Parameters: true(Boolean), 2(Long)
<==      Total: 1
==>  Preparing: SELECT p.id, p.name, p.price, p.stock, p.active, p.category_id FROM product p WHERE p.active = ? AND p.category_id IN (?) ORDER BY p.price DESC, p.id LIMIT ?
==> Parameters: true(Boolean), 2(Long), 5(Integer)
<==      Total: 5
total=13 pages=3 ids: [43, 37, 34, 31, 28]
PageInfo carries the total (45), the number of pages (5), and flags for next and previous. The second example shows that paging composes with the dynamic filter: the count query got the same WHERE as the data query, without you repeating it. The count query drops your ORDER BY, which is why it is cheap. The rule that keeps it safe is hidden in the name of the method. startPage does not page anything. It parks a request in a ThreadLocal, and the next MyBatis statement on that thread picks it up:
startPage(1, 5)ThreadLocal holdspage 1, size 5Bad: another query runs firstfindByIds([1]) takes the pagesearch() runs unpaged: 45 rowsGood: the lambda formstartPage(1,5).doSelectPageInfo(() -> mapper.search(f))PageHelper only knows “the nextMyBatis call on this thread”.The page request is parked in a ThreadLocal and consumed by whichever statement runs next, related or not (04-pagination.txt).
The two traps are real and each has a transcript. First, an unrelated query between startPage and the one you meant to page: Output, from output/04-pagination.txt:
## TRAP: startPage(1, 5), then an unrelated query, then the search you meant to page
unrelated query:
==>  Preparing: SELECT count(0) FROM product p WHERE p.id IN (?)
==> Parameters: 1(Long)
<==      Total: 1
==>  Preparing: SELECT p.id, p.name, p.price, p.stock, p.active, p.category_id FROM product p WHERE p.id IN ( ? ) ORDER BY p.id LIMIT ?
==> Parameters: 1(Long), 5(Integer)
<==      Total: 1
the search you meant to page:
==>  Preparing: SELECT p.id, p.name, p.price, p.stock, p.active, p.category_id FROM product p ORDER BY p.id
==> Parameters: 
<==      Total: 45
rows returned by the search: 45  (expected 5)
The lookup got a count query and a LIMIT 5 it never asked for, and the real search came back with all 45 rows, unpaged. Second, a startPage with no query after it at all (an early return, an exception):
## TRAP: startPage(1, 5) and no query afterwards
ThreadLocal page still set on this thread: true (pageSize=5)
next unrelated query on the same thread returned 5 rows instead of 7
==>  Preparing: SELECT count(0) FROM product p WHERE p.id IN (?, ?, ?, ?, ?, ?, ?)
==> Parameters: 1(Long), 2(Long), 3(Long), 4(Long), 5(Long), 6(Long), 7(Long)
<==      Total: 1
==>  Preparing: SELECT p.id, p.name, p.price, p.stock, p.active, p.category_id FROM product p WHERE p.id IN ( ? , ? , ? , ? , ? , ? , ? ) ORDER BY p.id LIMIT ?
==> Parameters: 1(Long), 2(Long), 3(Long), 4(Long), 5(Long), 6(Long), 7(Long), 5(Integer)
<==      Total: 5
after PageHelper.clearPage(): ThreadLocal page = null
The fingerprint of a leaked page. A query that should return 7 rows returns 5 and its SQL has a LIMIT nobody wrote — on whatever request next happens to reuse that pooled thread. The lambda form doSelectPageInfo(() -> ...) removes the first trap, because no other query can sit between the page request and yours. It is not a complete cure for the second, as the next run shows: a database error inside the lambda cleans up after itself, but a lambda that throws before it reaches MyBatis leaves the page parked.

Output, from output/04-pagination.txt:
## the lambda form when something fails: is a page left parked on the thread?
A) lambda throws before any query: caught boom
   ThreadLocal page afterwards: still set, pageSize=5
B) query fails inside the lambda: caught BadSqlGrammarException
   ThreadLocal page afterwards: null

So keep the lambda to one mapper call, do validation before it, and if you must call startPage directly, make the very next line the query and put PageHelper.clearPage() in a finally.
Intermediate: RowBounds, hand-written LIMIT, and OFFSET at depth

MyBatis has a built-in paging parameter, RowBounds(offset, limit). Without PageHelper it is client-side: the statement has no LIMIT, and MyBatis discards the first rows it reads. This was run in the @MybatisTest slice, where PageHelper is not present (next section):

Output, from output/05-mybatistest-slice.txt:

## RowBounds(offset=10, limit=5) with plain MyBatis: no LIMIT in the SQL, MyBatis skips rows on the client
==>  Preparing: SELECT p.id, p.name, p.price, p.stock, p.active, p.category_id FROM product p ORDER BY p.id
==> Parameters: 
ids returned: [11, 12, 13, 14, 15]

With PageHelper on the classpath, the same call is turned into SQL paging. Same Java, different SQL, depending only on a plugin:

Output, from output/04-pagination.txt:

## RowBounds(offset=10, limit=5) with PageHelper on the classpath: PageHelper turns it into LIMIT/OFFSET
==>  Preparing: SELECT p.id, p.name, p.price, p.stock, p.active, p.category_id FROM product p ORDER BY p.id LIMIT ? OFFSET ?
==> Parameters: 5(Integer), 10(Long)
<==      Total: 5
ids returned: [11, 12, 13, 14, 15]

The plugin-free option is to write the paging into the statement yourself, which keeps the SQL fully visible:

  <select id="pageByOffset" resultType="Product">
    SELECT <include refid="productColumns"/> FROM product p ORDER BY p.id LIMIT #{limit} OFFSET #{offset}
  </select>
## hand-written LIMIT/OFFSET (no plugin)
==>  Preparing: SELECT p.id, p.name, p.price, p.stock, p.active, p.category_id FROM product p ORDER BY p.id LIMIT ? OFFSET ?
==> Parameters: 5(Integer), 10(Integer)
<==      Total: 5
ids returned: [11, 12, 13, 14, 15]

One behaviour worth knowing: asking for a page past the end (with pagehelper.reasonable=false, as configured here) returns an empty list and still reports the real total, it does not clamp to the last page:

## last page and a page past the end (reasonable=false)
page 5: size=5 hasNextPage=false
page 9: size=0 total=45 list=Page{count=true, pageNum=9, pageSize=10, startRow=80, endRow=90, total=45, pages=5, reasonable=false, pageSizeZero=false}[]

All of these are OFFSET paging, which makes the database walk past every skipped row, so deep pages get slower. For the alternative (keyset or “scroll” paging) and why it exists, see Spring Data JPA Pagination and Sorting: Page vs Slice vs Keyset Scrolling; the idea (WHERE id > ?last ORDER BY id LIMIT ?) works in a MyBatis statement as well, though this demo does not include one.

Going deeper

Testing mappers with @MybatisTest, and what the slice leaves out

@MybatisTest starts only the MyBatis part of the application: the SqlSessionFactory, your mappers and a DataSource. It is to MyBatis what @DataJpaTest is to JPA (compare @DataJpaTest in Spring Boot 4.1 with Testcontainers). It is fast, and each test runs in a transaction that is rolled back. From AnnotationMapperTest.java:
@MybatisTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) // fresh database, so generated ids are the same on every run
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class AnnotationMapperTest {

    static final Transcript T = new Transcript("01-annotation-mapper.txt");
    @Autowired ProductMapper mapper;
Ask the slice what it contains and you learn two things, both easy to trip over. The service is absent, and so is the PageHelper plugin. The first is how slices work. The second means a mapper test never exercises your paging: Output, from output/05-mybatistest-slice.txt:
## beans in the @MybatisTest slice
mapper beans: [categoryMapper, productMapper, productXmlMapper]
ProductService (a @Service) present: false
SqlSessionFactory present: true
mapped statements registered: [com.ankurm.mybatis.mapper.ProductXmlMapper.search]
map-underscore-to-camel-case (from application.properties): true
plugins (interceptors) registered: []
DataSource URL: jdbc:h2:mem:<generated>
Note the DataSource URL: the application configures jdbc:h2:mem:shop, but the slice replaced the data source with a generated embedded one, which is the default behaviour of the slice. Your schema.sql and data.sql still ran against it. Test the paging in a @SpringBootTest instead; in that full context the plugin is there: Output, from output/06-versions-and-full-context.txt:
## plugins in the full @SpringBootTest context
plugins (interceptors) registered: [com.github.pagehelper.PageInterceptor]
Intermediate: the traps worth a test of their own

Because the tests assert what they print, each of the behaviours in this post is a failing test the day it changes: the number of statements for the JOIN versus the nested select, the Preparing text for every dynamic-SQL branch, the PageHelper page leak. When a new Boot or MyBatis release lands, running ./scripts/run-all.sh regenerates every transcript, and git diff output/ is the changelog that matters for your code.

The class that runs these with the full application context is PaginationTest.java, and the slice test is SliceTest.java.

Going deeper

Should you use MyBatis at all?

Choose it when the SQL is the product. Reporting queries, joins over a schema you do not control, database-specific functions, or a team that reads SQL fluently and wants to see exactly what runs: MyBatis makes those pleasant, and the logs in this post show how little magic there is. Skip it when your code is mostly create, read, update and delete on a model you own: Spring Data JPA or JdbcClient will get you there with less code, and you will not maintain XML. Know the costs before you start: the starter version is yours to track against Boot (neither starter is in the Boot BOM), mappers and XML are checked at runtime rather than compile time (a typo in a statement id shows up when the app starts or the method is called), and the silent-null mapping and unpaged-query traps above need discipline, not tooling, to avoid.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.