mybatis: MyBatis on Spring Boot 4.2.0 - annotation and XML mappers, result maps, dynamic SQL, PageHelper, @MybatisTest, seven real transcripts

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b3obqqePfZ9m2Jk5Ub
This commit is contained in:
Ankur Mhatre
2026-11-26 18:16:47 +05:30
co-authored by Claude Sonnet 5.5
parent fc8bc933d5
commit 8d8c28e2e5
35 changed files with 1332 additions and 0 deletions
+1
View File
@@ -13,6 +13,7 @@ Companion code for a series of posts on [ankurm.com](https://ankurm.com) coverin
| [`pagination/`](./pagination) | Spring Data JPA Pagination and Sorting: Page vs Slice vs Keyset Scrolling (Window API) | Spring Data JPA 4.1.2, Hibernate 7.4.13.Final, H2 2.4.240 | | [`pagination/`](./pagination) | Spring Data JPA Pagination and Sorting: Page vs Slice vs Keyset Scrolling (Window API) | Spring Data JPA 4.1.2, Hibernate 7.4.13.Final, H2 2.4.240 |
| [`jpa-auditing/`](./jpa-auditing) | JPA Auditing in Spring Boot 4: @CreatedDate, @LastModifiedBy and the Current User | Spring Data JPA 4.1.2, Spring Security 7.1.2, Hibernate 7.4.13.Final (+ Envers), H2 2.4.240 | | [`jpa-auditing/`](./jpa-auditing) | JPA Auditing in Spring Boot 4: @CreatedDate, @LastModifiedBy and the Current User | Spring Data JPA 4.1.2, Spring Security 7.1.2, Hibernate 7.4.13.Final (+ Envers), H2 2.4.240 |
| [`jdbcclient/`](./jdbcclient) | JdbcClient in Spring Framework 7: Modern JDBC Without JPA (vs JdbcTemplate) | Spring Framework 7.0.10, Spring Boot 4.1.2, HikariCP 7.0.2, H2 2.4.240 | | [`jdbcclient/`](./jdbcclient) | JdbcClient in Spring Framework 7: Modern JDBC Without JPA (vs JdbcTemplate) | Spring Framework 7.0.10, Spring Boot 4.1.2, HikariCP 7.0.2, H2 2.4.240 |
| [`mybatis/`](./mybatis) | MyBatis with Spring Boot 4: Mappers, Dynamic SQL and Pagination | MyBatis 3.5.19 (starter 4.1.0), PageHelper 6.1.1, Spring Boot 4.2.0, H2 2.5.252 |
Each module has its own `pom.xml`, a `docker-compose.yml` for its backing services, and a `docs/output/` directory holding the real, re-runnable transcripts that every number quoted in its post traces back to. There are no narrative doc chapters here &mdash; the deeper material for each post lives in accordions inside the post itself. Each module has its own `pom.xml`, a `docker-compose.yml` for its backing services, and a `docs/output/` directory holding the real, re-runnable transcripts that every number quoted in its post traces back to. There are no narrative doc chapters here &mdash; the deeper material for each post lives in accordions inside the post itself.
+1
View File
@@ -0,0 +1 @@
target/
+47
View File
@@ -0,0 +1,47 @@
# mybatis
Companion code for **MyBatis with Spring Boot 4: Mappers, Dynamic SQL and Pagination** on [ankurm.com](https://ankurm.com).
A small `category` / `product` schema on in-memory H2, annotation and XML mappers over it, result maps, dynamic SQL,
PageHelper pagination, and `@MybatisTest`. Six transcripts record what MyBatis really does, including the traps.
## Versions
| Component | Version |
|---|---|
| Spring Boot | 4.2.0 |
| 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) |
## Run it
```bash
./scripts/run-all.sh # runs the tests, which regenerate everything in output/
```
No Docker and no database to install.
## Source
| File | What it shows |
|---|---|
| [`ProductMapper.java`](src/main/java/com/ankurm/mybatis/mapper/ProductMapper.java) | annotation mapper: `@Select`, `@Insert` with generated keys, `@Update`, `@Delete`, `@Results` |
| [`ProductXmlMapper.java`](src/main/java/com/ankurm/mybatis/mapper/ProductXmlMapper.java) / [`ProductXmlMapper.xml`](src/main/resources/mappers/ProductXmlMapper.xml) | XML mapper: result map with association, dynamic SQL (`where`, `if`, `choose`, `foreach`, `set`, `bind`), `#{}` vs `${}` |
| [`CategoryMapper.xml`](src/main/resources/mappers/CategoryMapper.xml) | collection by nested result map (one JOIN) vs nested select (N+1) |
| [`ProductService.java`](src/main/java/com/ankurm/mybatis/service/ProductService.java) | the safe PageHelper form, `doSelectPageInfo` |
| [`application.properties`](src/main/resources/application.properties) | MyBatis and PageHelper settings, SQL logging |
## Captured output
| File | Shows |
|---|---|
| [`01-annotation-mapper.txt`](output/01-annotation-mapper.txt) | annotation mapper statements with the SQL MyBatis ran |
| [`02-result-maps.txt`](output/02-result-maps.txt) | association, JOIN collection (1 statement) vs nested select (4 statements) |
| [`03-dynamic-sql.txt`](output/03-dynamic-sql.txt) | the SQL every dynamic-SQL tag produces, empty `foreach` / `set` failures, `${}` vs `#{}` |
| [`04-pagination.txt`](output/04-pagination.txt) | PageHelper, its two traps, RowBounds, hand-written LIMIT/OFFSET |
| [`05-mybatistest-slice.txt`](output/05-mybatistest-slice.txt) | what `@MybatisTest` starts (and that PageHelper is not in it) |
| [`07-camel-case.txt`](output/07-camel-case.txt) | the missing `categoryId` when `map-underscore-to-camel-case` is off |
| [`06-versions-and-full-context.txt`](output/06-versions-and-full-context.txt) | the versions on the classpath for the run |
+58
View File
@@ -0,0 +1,58 @@
## 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
## findAll()
==> Preparing: SELECT id, name, price, stock, active, category_id FROM product ORDER BY id
==> Parameters:
<== Total: 45
rows: 45
## 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
## 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
## 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]
## 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
+35
View File
@@ -0,0 +1,35 @@
## 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]
## 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
## both strategies return the same product ids per category
identical: true
+59
View File
@@ -0,0 +1,59 @@
## 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
## empty category list is ignored, not turned into IN () (sorted by name so it is a new statement, not a cache hit)
==> Preparing: SELECT p.id, p.name, p.price, p.stock, p.active, p.category_id FROM product p ORDER BY p.name, p.id
==> Parameters:
<== Total: 45
## findByIds([2, 4, 6]) -> foreach
==> 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
==> Parameters: 2(Long), 4(Long), 6(Long)
<== Total: 3
## 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 only stock set -> <set> writes just that column
==> Preparing: UPDATE product SET stock = ? WHERE id = ?
==> Parameters: 99(Integer), 2(Long)
<== Updates: 1
## 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:
## 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]
## ${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
+66
View File
@@ -0,0 +1,66 @@
## 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]
## 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}[]
## 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)
## 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
## 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]
## 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]
## 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
+13
View File
@@ -0,0 +1,13 @@
## 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>
## 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]
@@ -0,0 +1,13 @@
## versions on the classpath (jar file names)
Spring Boot: 4.2.0
Spring Framework: 7.1.0
MyBatis: mybatis-3.5.19.jar
MyBatis-Spring: mybatis-spring-4.1.0.jar
Boot autoconfigure: mybatis-spring-boot-autoconfigure-4.1.0.jar
PageHelper: pagehelper-6.1.1.jar
PageHelper starter autoconfigure: pagehelper-spring-boot-autoconfigure-4.1.1.jar
Java: 25.0.5.1+2-LTS
H2: 2.5.252 (2026-09-23)
## plugins in the full @SpringBootTest context
plugins (interceptors) registered: [com.github.pagehelper.PageInterceptor]
+3
View File
@@ -0,0 +1,3 @@
## 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]
+62
View File
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.2.0</version>
</parent>
<groupId>com.ankurm</groupId>
<artifactId>mybatis-demo</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<java.version>25</java.version>
<maven.compiler.release>25</maven.compiler.release>
<mybatis-starter.version>4.1.0</mybatis-starter.version>
<pagehelper-starter.version>4.1.1</pagehelper-starter.version>
</properties>
<dependencies>
<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>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter-test</artifactId>
<version>${mybatis-starter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
# Regenerates every file in output/ by running the test suite (in-memory H2, no Docker, no database to install).
# The tests write the transcripts and assert the same facts, so a stale transcript fails the build.
set -euo pipefail
cd "$(dirname "$0")/.."
rm -f output/*.txt
mvn -B -q test
echo "wrote:"; ls output
@@ -0,0 +1,11 @@
package com.ankurm.mybatis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MybatisDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisDemoApplication.class, args);
}
}
@@ -0,0 +1,15 @@
package com.ankurm.mybatis.mapper;
import com.ankurm.mybatis.model.Category;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface CategoryMapper {
/** One JOIN, grouped into Category objects by a nested result map. */
List<Category> allWithProductsJoin();
/** One query for categories, then one more query per category (the N+1 shape). */
List<Category> allWithProductsNestedSelect();
}
@@ -0,0 +1,47 @@
package com.ankurm.mybatis.mapper;
import com.ankurm.mybatis.model.Product;
import com.ankurm.mybatis.model.ProductSummary;
import org.apache.ibatis.annotations.*;
import java.util.List;
import java.util.Optional;
/** The annotation style: SQL lives next to the method. Good for short, fixed statements. */
@Mapper
public interface ProductMapper {
@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);
@Update("UPDATE product SET stock = stock - #{qty} WHERE id = #{id} AND stock >= #{qty}")
int decrementStock(@Param("id") long id, @Param("qty") int qty);
@Delete("DELETE FROM product WHERE id = #{id}")
int delete(long id);
/** Explicit column mapping in annotation form: the same job a resultMap does in XML. */
@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);
/** The same query WITHOUT the @Results: only columns whose names happen to match get filled. */
@Select("SELECT id, name AS label, price AS cost FROM product WHERE id = #{id}")
Product findWithRenamedColumnsNoMapping(long id);
}
@@ -0,0 +1,41 @@
package com.ankurm.mybatis.mapper;
import com.ankurm.mybatis.model.Product;
import com.ankurm.mybatis.model.ProductFilter;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.RowBounds;
import java.util.List;
/** The XML style: the SQL is in src/main/resources/mappers/ProductXmlMapper.xml, matched by namespace and method name. */
@Mapper
public interface ProductXmlMapper {
/** Dynamic WHERE built from whichever filter fields are set. */
List<Product> search(@Param("f") ProductFilter filter);
/** Joins the category and maps it into {@code product.category} through an association. */
Product findWithCategory(long id);
/** WHERE id IN (...) built with foreach. */
List<Product> findByIds(@Param("ids") List<Long> ids);
/** UPDATE ... SET only for the columns that are not null. */
int updateSelective(Product product);
/** Multi-row insert with foreach. */
int insertAll(@Param("items") List<Product> items);
/** Uses ${} on purpose: the text is pasted into the SQL. */
List<Product> unsafeNameSearch(@Param("q") String q);
/** The same search with #{}: the text becomes a bind parameter. */
List<Product> safeNameSearch(@Param("q") String q);
/** Plain statement used to demonstrate RowBounds (client-side paging). */
List<Product> allOrdered(RowBounds rowBounds);
/** Manual paging in SQL. */
List<Product> pageByOffset(@Param("limit") int limit, @Param("offset") int offset);
}
@@ -0,0 +1,19 @@
package com.ankurm.mybatis.model;
import java.util.ArrayList;
import java.util.List;
public class Category {
private Long id;
private String name;
private List<Product> products = new ArrayList<>();
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public List<Product> getProducts() { return products; }
public void setProducts(List<Product> products) { this.products = products; }
@Override public String toString() { return "Category[" + id + ", " + name + ", products=" + products.size() + "]"; }
}
@@ -0,0 +1,40 @@
package com.ankurm.mybatis.model;
import java.math.BigDecimal;
/** A plain mutable bean: MyBatis fills it through setters, and can write generated keys back into {@code id}. */
public class Product {
private Long id;
private String name;
private BigDecimal price;
private Integer stock;
private Boolean active;
private Long categoryId;
private Category category; // only filled by result maps that join the category table
public Product() {}
public Product(String name, BigDecimal price, int stock, boolean active, long categoryId) {
this.name = name; this.price = price; this.stock = stock; this.active = active; this.categoryId = categoryId;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public BigDecimal getPrice() { return price; }
public void setPrice(BigDecimal price) { this.price = price; }
public Integer getStock() { return stock; }
public void setStock(Integer stock) { this.stock = stock; }
public Boolean getActive() { return active; }
public void setActive(Boolean active) { this.active = active; }
public Long getCategoryId() { return categoryId; }
public void setCategoryId(Long categoryId) { this.categoryId = categoryId; }
public Category getCategory() { return category; }
public void setCategory(Category category) { this.category = category; }
@Override public String toString() {
return "Product[" + id + ", " + name + ", " + price + ", stock=" + stock + ", active=" + active
+ ", categoryId=" + categoryId + (category != null ? ", category=" + category.getName() : "") + "]";
}
}
@@ -0,0 +1,10 @@
package com.ankurm.mybatis.model;
import java.math.BigDecimal;
import java.util.List;
/** Search criteria. Every field is optional; null means "do not filter on this". */
public record ProductFilter(String nameContains, BigDecimal minPrice, BigDecimal maxPrice,
Boolean active, List<Long> categoryIds, String sort) {
public static ProductFilter none() { return new ProductFilter(null, null, null, null, null, null); }
}
@@ -0,0 +1,6 @@
package com.ankurm.mybatis.model;
import java.math.BigDecimal;
/** A Java record works as a result type: MyBatis calls the canonical constructor and matches columns by name. */
public record ProductSummary(Long id, String name, BigDecimal price) {}
@@ -0,0 +1,23 @@
package com.ankurm.mybatis.service;
import com.ankurm.mybatis.mapper.ProductXmlMapper;
import com.ankurm.mybatis.model.Product;
import com.ankurm.mybatis.model.ProductFilter;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
@Service
public class ProductService {
private final ProductXmlMapper mapper;
public ProductService(ProductXmlMapper mapper) { this.mapper = mapper; }
/**
* The safe PageHelper form: the lambda guarantees the very next MyBatis call is the one being paged,
* and the page state is always cleaned up afterwards.
*/
public PageInfo<Product> page(ProductFilter filter, int pageNum, int pageSize) {
return PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> mapper.search(filter));
}
}
@@ -0,0 +1,14 @@
spring.application.name=mybatis-demo
spring.datasource.url=jdbc:h2:mem:shop;DB_CLOSE_DELAY=-1
spring.main.banner-mode=off
# 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
+10
View File
@@ -0,0 +1,10 @@
INSERT INTO category(name) VALUES ('Books'), ('Gadgets'), ('Kitchen');
-- 45 deterministic products: ids 1..45, category cycles 1,2,3; every 10th product is inactive
INSERT INTO product(name, price, stock, active, category_id)
SELECT 'Product ' || LPAD(CAST(x AS VARCHAR), 2, '0'),
10 + x * 2.5,
MOD(x * 7, 20),
MOD(x, 10) <> 0,
MOD(x, 3) + 1
FROM SYSTEM_RANGE(1, 45);
@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ankurm.mybatis.mapper.CategoryMapper">
<!-- Nested result map: rows of one JOIN are folded into Category objects, each holding its products. -->
<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>
<!-- Nested select: the collection runs a second statement per category row. -->
<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>
<select id="allWithProductsNestedSelect" resultMap="categoryNestedSelectMap">
SELECT id, name FROM category ORDER BY id
</select>
</mapper>
@@ -0,0 +1,93 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ankurm.mybatis.mapper.ProductXmlMapper">
<!-- A reusable column list. -->
<sql id="productColumns">p.id, p.name, p.price, p.stock, p.active, p.category_id</sql>
<!-- 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>
<!-- 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>
<select id="findByIds" resultType="Product">
SELECT <include refid="productColumns"/> FROM product p
WHERE p.id IN
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
ORDER BY p.id
</select>
<!-- <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>
<insert id="insertAll" useGeneratedKeys="true" keyProperty="id">
INSERT INTO product(name, price, stock, active, category_id) VALUES
<foreach collection="items" item="i" separator=",">
(#{i.name}, #{i.price}, #{i.stock}, #{i.active}, #{i.categoryId})
</foreach>
</insert>
<!-- ${q} is pasted into the SQL text. Never do this with user input. -->
<select id="unsafeNameSearch" resultType="Product">
SELECT <include refid="productColumns"/> FROM product p WHERE p.name LIKE '%${q}%' ORDER BY p.id
</select>
<select id="safeNameSearch" resultType="Product">
SELECT <include refid="productColumns"/> FROM product p WHERE p.name LIKE CONCAT('%', #{q}, '%') ORDER BY p.id
</select>
<select id="allOrdered" resultType="Product">
SELECT <include refid="productColumns"/> FROM product p ORDER BY p.id
</select>
<select id="pageByOffset" resultType="Product">
SELECT <include refid="productColumns"/> FROM product p ORDER BY p.id LIMIT #{limit} OFFSET #{offset}
</select>
</mapper>
+13
View File
@@ -0,0 +1,13 @@
CREATE TABLE category (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE product (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(10,2) NOT NULL,
stock INT NOT NULL,
active BOOLEAN NOT NULL,
category_id BIGINT NOT NULL REFERENCES category(id)
);
@@ -0,0 +1,102 @@
package com.ankurm.mybatis;
import com.ankurm.mybatis.mapper.ProductMapper;
import com.ankurm.mybatis.model.Product;
import com.ankurm.mybatis.model.ProductSummary;
import org.junit.jupiter.api.*;
import org.mybatis.spring.boot.test.autoconfigure.MybatisTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Uses @MybatisTest: only the MyBatis slice (SqlSessionFactory, mappers, DataSource) starts, and every test
* runs in a transaction that is rolled back. Writes output/01-annotation-mapper.txt.
*/
@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;
@AfterAll static void write() { T.write(); }
@Test @Order(1) void selectOneAndMany() {
var one = SqlLog.capture(() -> mapper.findById(7));
T.head("findById(7)").lines(one.sql()).line("result: " + one.result().orElseThrow());
assertThat(one.result()).isPresent();
var none = SqlLog.capture(() -> mapper.findById(999));
T.head("findById(999) (no such row, returns Optional)").lines(none.sql()).line("result: " + none.result());
assertThat(none.result()).isEmpty();
var all = SqlLog.capture(() -> mapper.findAll());
T.head("findAll()").lines(all.sql()).line("rows: " + all.result().size());
assertThat(all.result()).hasSize(45);
}
@Test @Order(2) void recordResult() {
var top = SqlLog.capture(() -> mapper.topPriced(3));
T.head("topPriced(3) -> List<ProductSummary> (a record)").lines(top.sql());
top.result().forEach(r -> T.line(" " + r));
assertThat(top.result()).hasSize(3);
assertThat(top.result().getFirst()).isInstanceOf(ProductSummary.class);
// product 45 is the most expensive (10 + 45 * 2.5 = 122.50) and active
assertThat(top.result().getFirst().id()).isEqualTo(45L);
}
@Test @Order(3) void insertWithGeneratedKey() {
Product p = new Product("Desk lamp", new BigDecimal("39.90"), 12, true, 2);
T.head("insert (id before: " + p.getId() + ")");
var r = SqlLog.capture(() -> mapper.insert(p));
T.lines(r.sql()).line("rows affected: " + r.result()).line("id after (written back by useGeneratedKeys): " + p.getId());
assertThat(p.getId()).isEqualTo(46L);
}
@Test @Order(4) void conditionalUpdate() {
var ok = SqlLog.capture(() -> mapper.decrementStock(1, 3));
T.head("decrementStock(id=1, qty=3) (stock of product 1 is 7)").lines(ok.sql()).line("rows affected: " + ok.result());
var tooMany = SqlLog.capture(() -> mapper.decrementStock(1, 500));
T.head("decrementStock(id=1, qty=500) (guard in WHERE: stock >= qty)").lines(tooMany.sql())
.line("rows affected: " + tooMany.result());
assertThat(ok.result()).isEqualTo(1);
assertThat(tooMany.result()).isZero();
}
@Test @Order(5) void renamedColumns() {
Product mapped = mapper.findWithRenamedColumns(7);
mapper.findWithRenamedColumnsNoMapping(7);
Product unmapped = mapper.findWithRenamedColumnsNoMapping(7);
T.head("columns aliased to label / cost (id keeps its name)");
T.line("with @Results: " + mapped);
T.line("without @Results: " + unmapped);
assertThat(mapped.getName()).isEqualTo("Product 07");
assertThat(unmapped.getId()).isEqualTo(7L);
assertThat(unmapped.getName()).isNull();
assertThat(unmapped.getPrice()).isNull();
}
@Test @Order(6) void deleteRollsBack() {
var d = SqlLog.capture(() -> mapper.delete(1));
T.head("delete(1)").lines(d.sql()).line("rows affected: " + d.result());
Optional<Product> after = mapper.findById(1);
T.line("findById(1) inside the same test transaction: " + after);
assertThat(after).isEmpty();
}
@Test @Order(7) void previousTestsWereRolledBack() {
// @MybatisTest wraps each test in a transaction and rolls it back: the delete and insert above are gone.
List<Product> all = mapper.findAll();
T.head("a later test sees the original data again (rollback)");
T.line("findAll().size() = " + all.size() + ", findById(1) present = " + mapper.findById(1).isPresent());
assertThat(all).hasSize(45);
assertThat(mapper.findById(1)).isPresent();
}
}
@@ -0,0 +1,29 @@
package com.ankurm.mybatis;
import com.ankurm.mybatis.mapper.ProductMapper;
import com.ankurm.mybatis.model.Product;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.mybatis.spring.boot.test.autoconfigure.MybatisTest;
import org.springframework.beans.factory.annotation.Autowired;
import static org.assertj.core.api.Assertions.assertThat;
/** The one setting beginners trip on: without map-underscore-to-camel-case, category_id never reaches categoryId. Writes output/07-camel-case.txt. */
@MybatisTest(properties = "mybatis.configuration.map-underscore-to-camel-case=false")
class CamelCaseTest {
static final Transcript T = new Transcript("07-camel-case.txt");
@Autowired ProductMapper mapper;
@AfterAll static void write() { T.write(); }
@Test void withoutCamelCaseMapping() {
Product p = mapper.findById(7).orElseThrow();
T.head("mybatis.configuration.map-underscore-to-camel-case=false (MyBatis's own default)");
T.line("columns in the SELECT: id, name, price, stock, active, category_id");
T.line("result: " + p);
assertThat(p.getName()).isEqualTo("Product 07");
assertThat(p.getCategoryId()).isNull();
}
}
@@ -0,0 +1,97 @@
package com.ankurm.mybatis;
import com.ankurm.mybatis.mapper.ProductXmlMapper;
import com.ankurm.mybatis.model.Product;
import com.ankurm.mybatis.model.ProductFilter;
import org.junit.jupiter.api.*;
import org.mybatis.spring.boot.test.autoconfigure.MybatisTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import java.math.BigDecimal;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Dynamic SQL: if/where/choose/foreach/set/bind, and #{} versus ${}. Writes output/03-dynamic-sql.txt. */
@MybatisTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) // fresh database, so generated ids are the same on every run
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class DynamicSqlTest {
static final Transcript T = new Transcript("03-dynamic-sql.txt");
@Autowired ProductXmlMapper mapper;
@AfterAll static void write() { T.write(); }
private void show(String title, ProductFilter f, int expectedRows) {
var r = SqlLog.capture(() -> mapper.search(f));
T.head(title).lines(r.sql());
assertThat(r.result()).hasSize(expectedRows);
}
@Test @Order(1) void searchVariants() {
show("no filters: <where> disappears completely", ProductFilter.none(), 45);
show("only active = true: <where> appears, no stray AND",
new ProductFilter(null, null, null, true, null, null), 41);
show("name contains '1', price between 20 and 60",
new ProductFilter("1", new BigDecimal("20"), new BigDecimal("60"), null, null, null), 10); // product 04..20 by price; of those, 10..19 contain "1"
show("categories 1 and 3, sorted by price desc (choose/when)",
new ProductFilter(null, null, null, null, List.of(1L, 3L), "price_desc"), 30);
show("empty category list is ignored, not turned into IN () (sorted by name so it is a new statement, not a cache hit)",
new ProductFilter(null, null, null, null, List.of(), "name"), 45);
}
@Test @Order(2) void foreachIn() {
var r = SqlLog.capture(() -> mapper.findByIds(List.of(2L, 4L, 6L)));
T.head("findByIds([2, 4, 6]) -> foreach").lines(r.sql());
assertThat(r.result()).extracting(Product::getId).containsExactly(2L, 4L, 6L);
}
@Test @Order(3) void emptyForeachIsInvalidSql() {
T.head("findByIds([]) -> foreach over an empty list produces 'IN' with nothing after it");
assertThatThrownBy(() -> mapper.findByIds(List.of())).satisfies(e -> {
Throwable root = e; while (root.getCause() != null) root = root.getCause();
T.line("exception: " + e.getClass().getSimpleName());
T.line("root cause: " + root.getClass().getSimpleName() + " - " + root.getMessage().lines().findFirst().orElse(""));
});
}
@Test @Order(4) void setOnlyWhatIsNotNull() {
Product patch = new Product();
patch.setId(2L);
patch.setStock(99);
var r = SqlLog.capture(() -> mapper.updateSelective(patch));
T.head("updateSelective with only stock set -> <set> writes just that column").lines(r.sql());
assertThat(mapper.findWithCategory(2).getStock()).isEqualTo(99);
assertThat(mapper.findWithCategory(2).getName()).isEqualTo("Product 02");
Product nothing = new Product();
nothing.setId(2L);
T.head("updateSelective with nothing set -> <set> has no content, the SQL is broken");
assertThatThrownBy(() -> mapper.updateSelective(nothing)).satisfies(e -> {
Throwable root = e; while (root.getCause() != null) root = root.getCause();
T.line("root cause: " + root.getClass().getSimpleName() + " - " + root.getMessage().lines().findFirst().orElse(""));
});
}
@Test @Order(5) void multiRowInsert() {
List<Product> items = List.of(new Product("A", new BigDecimal("1.00"), 1, true, 1),
new Product("B", new BigDecimal("2.00"), 2, true, 1));
var r = SqlLog.capture(() -> mapper.insertAll(items));
T.head("insertAll -> one INSERT with two value tuples").lines(r.sql());
T.line("generated ids written back: " + items.stream().map(Product::getId).toList());
assertThat(items).allSatisfy(p -> assertThat(p.getId()).isNotNull());
}
@Test @Order(6) void dollarVersusHash() {
String attack = "zzz' OR '1'='1' OR name LIKE '";
var unsafe = SqlLog.capture(() -> mapper.unsafeNameSearch(attack));
T.head("${q} with q = " + attack).lines(unsafe.sql()).line("rows returned: " + unsafe.result().size());
var safe = SqlLog.capture(() -> mapper.safeNameSearch(attack));
T.head("#{q} with q = " + attack).lines(safe.sql()).line("rows returned: " + safe.result().size());
assertThat(unsafe.result()).hasSize(45); // the attacker's OR clause became part of the SQL
assertThat(safe.result()).isEmpty();
}
}
@@ -0,0 +1,45 @@
package com.ankurm.mybatis;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootVersion;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
/** Compares the full context with the slice, and records the versions that were really on the classpath. Writes output/06-versions-and-full-context.txt. */
@SpringBootTest
class FullContextTest {
static final Transcript T = new Transcript("06-versions-and-full-context.txt");
@Autowired SqlSessionFactory factory;
@Autowired DataSource dataSource;
@AfterAll static void write() { T.write(); }
private static String jarVersion(Class<?> c) {
String p = c.getProtectionDomain().getCodeSource().getLocation().getPath();
return p.substring(p.lastIndexOf('/') + 1);
}
@Test void report() throws Exception {
T.head("versions on the classpath (jar file names)");
T.line("Spring Boot: " + SpringBootVersion.getVersion());
T.line("Spring Framework: " + org.springframework.core.SpringVersion.getVersion());
T.line("MyBatis: " + jarVersion(org.apache.ibatis.session.SqlSession.class));
T.line("MyBatis-Spring: " + jarVersion(org.mybatis.spring.SqlSessionFactoryBean.class));
T.line("Boot autoconfigure: " + jarVersion(org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration.class));
T.line("PageHelper: " + jarVersion(com.github.pagehelper.PageHelper.class));
T.line("PageHelper starter autoconfigure: " + jarVersion(com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration.class));
T.line("Java: " + Runtime.version());
try (Connection c = dataSource.getConnection()) {
T.line("H2: " + c.getMetaData().getDatabaseProductVersion());
}
T.head("plugins in the full @SpringBootTest context");
T.line("plugins (interceptors) registered: "
+ factory.getConfiguration().getInterceptors().stream().map(i -> i.getClass().getName()).toList());
}
}
@@ -0,0 +1,128 @@
package com.ankurm.mybatis;
import com.ankurm.mybatis.mapper.ProductXmlMapper;
import com.ankurm.mybatis.model.Product;
import com.ankurm.mybatis.model.ProductFilter;
import com.ankurm.mybatis.service.ProductService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.RowBounds;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/** PageHelper, its traps, RowBounds, and hand-written LIMIT/OFFSET. Writes output/04-pagination.txt. */
@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class PaginationTest {
static final Transcript T = new Transcript("04-pagination.txt");
@Autowired ProductService service;
@Autowired ProductXmlMapper mapper;
@AfterAll static void write() { T.write(); }
@Test @Order(1) void pageHelperService() {
var r = SqlLog.capture(() -> service.page(ProductFilter.none(), 2, 10));
PageInfo<Product> p = r.result();
T.head("service.page(none, pageNum=2, pageSize=10) -> PageHelper rewrote the query and added a count query").lines(r.sql());
T.line("pageNum=" + p.getPageNum() + " pageSize=" + p.getPageSize() + " size=" + p.getSize()
+ " total=" + p.getTotal() + " pages=" + p.getPages());
T.line("hasPreviousPage=" + p.isHasPreviousPage() + " hasNextPage=" + p.isHasNextPage());
T.line("ids on this page: " + p.getList().stream().map(Product::getId).toList());
assertThat(p.getTotal()).isEqualTo(45);
assertThat(p.getPages()).isEqualTo(5);
assertThat(p.getList()).extracting(Product::getId).containsExactly(11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L);
}
@Test @Order(2) void filteredPage() {
var r = SqlLog.capture(() -> service.page(new ProductFilter(null, null, null, true, List.of(2L), "price_desc"), 1, 5));
PageInfo<Product> p = r.result();
T.head("filter + sort + page: the dynamic SQL and the paging compose").lines(r.sql());
T.line("total=" + p.getTotal() + " pages=" + p.getPages() + " ids: " + p.getList().stream().map(Product::getId).toList());
assertThat(p.getTotal()).isEqualTo(13); // category 2 holds 15 products; ids 10 and 40 are inactive
}
@Test @Order(3) void lastPageAndOutOfRange() {
PageInfo<Product> last = service.page(ProductFilter.none(), 5, 10);
PageInfo<Product> beyond = service.page(ProductFilter.none(), 9, 10);
T.head("last page and a page past the end (reasonable=false)");
T.line("page 5: size=" + last.getSize() + " hasNextPage=" + last.isHasNextPage());
T.line("page 9: size=" + beyond.getSize() + " total=" + beyond.getTotal() + " list=" + beyond.getList());
assertThat(last.getSize()).isEqualTo(5);
assertThat(beyond.getList()).isEmpty();
}
@Test @Order(4) void trapQueryInBetween() {
// BAD: startPage() applies to the NEXT MyBatis call, whatever it is.
PageHelper.startPage(1, 5);
var lookup = SqlLog.capture(() -> mapper.findByIds(List.of(1L))); // unrelated query steals the page
var wanted = SqlLog.capture(() -> mapper.search(ProductFilter.none())); // this one is no longer paged
T.head("TRAP: startPage(1, 5), then an unrelated query, then the search you meant to page");
T.line("unrelated query:").lines(lookup.sql());
T.line("the search you meant to page:").lines(wanted.sql());
T.line("rows returned by the search: " + wanted.result().size() + " (expected 5)");
assertThat(wanted.result()).hasSize(45);
}
@Test @Order(5) void trapStartPageWithoutQuery() {
PageHelper.startPage(1, 5); // nobody runs a query after this
Page<Object> local = PageHelper.getLocalPage();
T.head("TRAP: startPage(1, 5) and no query afterwards");
T.line("ThreadLocal page still set on this thread: " + (local != null) + " (pageSize=" + (local == null ? "-" : local.getPageSize()) + ")");
var next = SqlLog.capture(() -> mapper.findByIds(List.of(1L, 2L, 3L, 4L, 5L, 6L, 7L)));
T.line("next unrelated query on the same thread returned " + next.result().size() + " rows instead of 7");
T.lines(next.sql());
assertThat(next.result()).hasSize(5);
PageHelper.clearPage();
assertThat(PageHelper.getLocalPage()).isNull();
T.line("after PageHelper.clearPage(): ThreadLocal page = " + PageHelper.getLocalPage());
}
@Test @Order(6) void rowBoundsIsClientSide() {
var r = SqlLog.capture(() -> mapper.allOrdered(new RowBounds(10, 5)));
T.head("RowBounds(offset=10, limit=5) with PageHelper on the classpath: PageHelper turns it into LIMIT/OFFSET");
T.lines(r.sql());
T.line("ids returned: " + r.result().stream().map(Product::getId).toList());
assertThat(r.sql().getFirst()).contains("LIMIT");
assertThat(r.result()).extracting(Product::getId).containsExactly(11L, 12L, 13L, 14L, 15L);
}
@Test @Order(7) void manualLimitOffset() {
var r = SqlLog.capture(() -> mapper.pageByOffset(5, 10));
T.head("hand-written LIMIT/OFFSET (no plugin)");
T.lines(r.sql());
T.line("ids returned: " + r.result().stream().map(Product::getId).toList());
assertThat(r.result()).extracting(Product::getId).containsExactly(11L, 12L, 13L, 14L, 15L);
}
@Test @Order(8) void lambdaFormWhenSomethingFails() {
T.head("the lambda form when something fails: is a page left parked on the thread?");
// A: the lambda throws before it reaches MyBatis
try {
PageHelper.startPage(1, 5).doSelectPageInfo(() -> { throw new IllegalStateException("boom"); });
} catch (IllegalStateException e) {
T.line("A) lambda throws before any query: caught " + e.getMessage());
}
T.line(" ThreadLocal page afterwards: " + (PageHelper.getLocalPage() == null ? "null" : "still set, pageSize=" + PageHelper.getLocalPage().getPageSize()));
boolean leakedA = PageHelper.getLocalPage() != null;
PageHelper.clearPage();
// B: the query inside the lambda fails in the database (empty IN list)
try {
PageHelper.startPage(1, 5).doSelectPageInfo(() -> mapper.findByIds(List.of()));
} catch (RuntimeException e) {
T.line("B) query fails inside the lambda: caught " + e.getClass().getSimpleName());
}
T.line(" ThreadLocal page afterwards: " + (PageHelper.getLocalPage() == null ? "null" : "still set, pageSize=" + PageHelper.getLocalPage().getPageSize()));
boolean leakedB = PageHelper.getLocalPage() != null;
PageHelper.clearPage();
assertThat(leakedA).isTrue();
assertThat(leakedB).isFalse();
}
}
@@ -0,0 +1,62 @@
package com.ankurm.mybatis;
import com.ankurm.mybatis.mapper.CategoryMapper;
import com.ankurm.mybatis.mapper.ProductXmlMapper;
import com.ankurm.mybatis.model.Category;
import com.ankurm.mybatis.model.Product;
import org.junit.jupiter.api.*;
import org.mybatis.spring.boot.test.autoconfigure.MybatisTest;
import org.springframework.beans.factory.annotation.Autowired;
import static org.assertj.core.api.Assertions.assertThat;
/** XML result maps: association (one-to-one), collection by JOIN, collection by nested select (N+1). Writes output/02-result-maps.txt. */
@MybatisTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ResultMapTest {
static final Transcript T = new Transcript("02-result-maps.txt");
@Autowired ProductXmlMapper products;
@Autowired CategoryMapper categories;
@AfterAll static void write() { T.write(); }
@Test @Order(1) void association() {
var r = SqlLog.capture(() -> products.findWithCategory(7));
T.head("findWithCategory(7) -> association fills product.category from joined columns").lines(r.sql())
.line("result: " + r.result());
assertThat(r.result().getCategory().getName()).isEqualTo("Gadgets");
}
@Test @Order(2) void collectionByJoin() {
var r = SqlLog.capture(() -> categories.allWithProductsJoin());
T.head("allWithProductsJoin() -> one statement, nested result map folds rows into objects").lines(r.sql());
r.result().forEach(c -> T.line(" " + c));
T.line("statements executed: " + r.statements());
assertThat(r.statements()).isEqualTo(1);
assertThat(r.result()).hasSize(3);
assertThat(r.result().stream().mapToInt(c -> c.getProducts().size()).sum()).isEqualTo(41); // 45 minus 4 inactive (10,20,30,40)
}
@Test @Order(3) void collectionByNestedSelect() {
var r = SqlLog.capture(() -> categories.allWithProductsNestedSelect());
T.head("allWithProductsNestedSelect() -> one query, then one more per category").lines(r.sql());
r.result().forEach(c -> T.line(" " + c));
T.line("statements executed: " + r.statements());
assertThat(r.statements()).isEqualTo(4); // 1 + 3 categories
assertThat(r.result().stream().mapToInt(c -> c.getProducts().size()).sum()).isEqualTo(41);
}
@Test @Order(4) void sameCategoryObjectsEqualResults() {
var a = categories.allWithProductsJoin();
var b = categories.allWithProductsNestedSelect();
boolean same = true;
for (int i = 0; i < a.size(); i++) {
same &= a.get(i).getProducts().stream().map(Product::getId).toList()
.equals(b.get(i).getProducts().stream().map(Product::getId).toList());
}
T.head("both strategies return the same product ids per category");
T.line("identical: " + same);
assertThat(same).isTrue();
}
}
@@ -0,0 +1,58 @@
package com.ankurm.mybatis;
import com.ankurm.mybatis.service.ProductService;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.jupiter.api.*;
import org.mybatis.spring.boot.test.autoconfigure.MybatisTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.TestPropertySource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
/** What @MybatisTest does and does not start. Writes output/05-mybatistest-slice.txt. */
@MybatisTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SliceTest {
static final Transcript T = new Transcript("05-mybatistest-slice.txt");
@Autowired ApplicationContext ctx;
@Autowired SqlSessionFactory factory;
@Autowired DataSource dataSource;
@Autowired com.ankurm.mybatis.mapper.ProductXmlMapper xmlMapper;
@AfterAll static void write() { T.write(); }
@Test @Order(1) void whatTheSliceContains() throws Exception {
T.head("beans in the @MybatisTest slice");
T.line("mapper beans: " + Arrays.stream(ctx.getBeanNamesForType(Object.class))
.filter(n -> n.endsWith("Mapper")).sorted().toList());
T.line("ProductService (a @Service) present: " + (ctx.getBeanNamesForType(ProductService.class).length > 0));
T.line("SqlSessionFactory present: " + (factory != null));
T.line("mapped statements registered: " + factory.getConfiguration().getMappedStatementNames().stream()
.filter(n -> n.contains(".ProductXmlMapper.search")).sorted().toList());
T.line("map-underscore-to-camel-case (from application.properties): "
+ factory.getConfiguration().isMapUnderscoreToCamelCase());
T.line("plugins (interceptors) registered: "
+ factory.getConfiguration().getInterceptors().stream().map(i -> i.getClass().getSimpleName()).toList());
try (Connection c = dataSource.getConnection()) {
T.line("DataSource URL: " + c.getMetaData().getURL().replaceAll("jdbc:h2:mem:[^;]*", "jdbc:h2:mem:<generated>"));
}
assertThat(ctx.getBeanNamesForType(ProductService.class)).isEmpty();
assertThat(factory.getConfiguration().getInterceptors()).isEmpty();
}
@Test @Order(2) void rowBoundsWithoutPageHelper() {
var r = SqlLog.capture(() -> xmlMapper.allOrdered(new org.apache.ibatis.session.RowBounds(10, 5)));
T.head("RowBounds(offset=10, limit=5) with plain MyBatis: no LIMIT in the SQL, MyBatis skips rows on the client");
T.lines(r.sql());
T.line("ids returned: " + r.result().stream().map(com.ankurm.mybatis.model.Product::getId).toList());
assertThat(r.sql().getFirst()).doesNotContain("LIMIT");
assertThat(r.result()).hasSize(5);
}
}
@@ -0,0 +1,39 @@
package com.ankurm.mybatis;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
/** Captures MyBatis's own DEBUG lines ("==> Preparing", "==> Parameters", "<== Total") for the mapper package. */
final class SqlLog {
private SqlLog() {}
static <T> Captured<T> capture(Supplier<T> action) {
Logger logger = (Logger) LoggerFactory.getLogger("com.ankurm.mybatis.mapper");
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.start();
logger.addAppender(appender);
try {
T result = action.get();
List<String> lines = new ArrayList<>();
for (ILoggingEvent e : appender.list) {
String m = e.getFormattedMessage();
if (m.startsWith("=") || m.startsWith("<=")) lines.add(m);
}
return new Captured<>(result, lines);
} finally {
logger.detachAppender(appender);
}
}
static Captured<Void> run(Runnable r) { return capture(() -> { r.run(); return null; }); }
record Captured<T>(T result, List<String> sql) {
long statements() { return sql.stream().filter(s -> s.contains("Preparing:")).count(); }
}
}
@@ -0,0 +1,27 @@
package com.ankurm.mybatis;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
/** Collects what a test prints and writes it to output/NN-name.txt, so the file is what the test really saw. */
final class Transcript {
private final StringBuilder sb = new StringBuilder();
private final String file;
Transcript(String file) { this.file = file; }
Transcript line(String s) { sb.append(s).append('\n'); return this; }
Transcript blank() { return line(""); }
Transcript head(String s) { if (sb.length() > 0) blank(); return line("## " + s); }
Transcript lines(List<String> l) { l.forEach(this::line); return this; }
void write() {
try {
Path dir = Path.of("output");
Files.createDirectories(dir);
Files.writeString(dir.resolve(file), sb.toString());
} catch (IOException e) { throw new RuntimeException(e); }
}
}