Who this course is for
You know Java, you can write a JOIN, and you have either fought Hibernate or inherited a
pile of hand-rolled JDBC. You want a data-access layer where the SQL is visible, reviewable
and tunable — but you do not want to write ResultSet loops for the rest of your life.
No prior MyBatis knowledge is assumed. Chapters build on one another, but each one opens with the context it needs, so you can also land here from a search engine and get a complete answer.
Syllabus
What is MyBatis and why use it
The problem it solves, SQL mapper vs full ORM, an honest comparison with Hibernate and plain JDBC, and a walk through the runtime architecture.
02Installation and project setup
Maven and Gradle coordinates, the H2/MySQL sample schema, building the
SqlSessionFactory, and running your first query end to end.
The configuration file
Every element of mybatis-config.xml: properties, settings, type aliases,
type handlers, environments, data sources and mapper registration.
Mapper XML in depth
select, insert, update, delete,
reusable <sql> fragments, and the security-critical difference between
#{} and ${}.
Annotation-based mappers
@Select, @Results, @Param, @Options,
SQL providers and the SQL builder DSL — plus when XML is still the right call.
CRUD operations
A full create/read/update/delete implementation with generated keys, batch inserts, pagination and optimistic locking.
07Dynamic SQL
if, choose, where, set,
trim, foreach and bind — with the generated SQL
shown for each branch.
ResultMaps, associations, collections
Turning joined rows into object graphs, nested results vs nested selects, discriminators, and how to detect and kill N+1 queries.
09Caching
The session-local first level cache, the namespace second level cache, eviction
policies, cache-ref, Redis, and when caching hurts.
Transactions and sessions
Session scope rules, commit/rollback semantics, isolation levels, executor types and batch flushing.
11Spring Boot integration
The starter, application.yml properties, @MapperScan,
SqlSessionTemplate, declarative transactions and multiple data sources.
Plugins, type handlers, generation
Writing interceptors, custom TypeHandlers for enums and JSON columns,
stored procedures, and MyBatis Generator.
Testing your mappers
Fast H2 tests, realistic Testcontainers tests, the @MybatisTest slice,
fixtures and asserting the SQL that actually ran.
Best practices and pitfalls
Naming, layout, mapper design rules, a performance checklist and the twelve mistakes behind most production incidents.
15FAQ and interview questions
Forty questions with direct answers, plus a one-page cheat sheet you can keep open while you work.
StartBegin the course →
Chapter 1 takes about twelve minutes and gives you the mental model everything else depends on.
The sample schema
Every chapter uses the same tiny e-commerce schema. Four tables are enough to demonstrate one-to-one, one-to-many, enums, JSON columns, soft deletes and optimistic locking.
CREATE TABLE app_user (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
user_name VARCHAR(60) NOT NULL UNIQUE,
email VARCHAR(160) NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
version INT NOT NULL DEFAULT 0
);
CREATE TABLE address (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
user_id BIGINT NOT NULL REFERENCES app_user(id),
line1 VARCHAR(160) NOT NULL,
city VARCHAR(80) NOT NULL,
country CHAR(2) NOT NULL
);
CREATE TABLE product (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
sku VARCHAR(40) NOT NULL UNIQUE,
name VARCHAR(160) NOT NULL,
price DECIMAL(12,2) NOT NULL
);
CREATE TABLE customer_order (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
user_id BIGINT NOT NULL REFERENCES app_user(id),
total DECIMAL(12,2) NOT NULL,
status VARCHAR(20) NOT NULL,
placed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_order_user ON customer_order(user_id);
Project layout used throughout
Mapper interfaces live next to the rest of the Java code; mapper XML lives under
src/main/resources in a folder that mirrors the package. That mirroring is what
lets MyBatis (and the Spring Boot starter) find the XML for an interface automatically.
mybatis-demo
├── pom.xml
└── src
├── main
│ ├── java/com/bitsnippets/shop
│ │ ├── ShopApplication.java
│ │ ├── domain/ User.java, Address.java, Order.java, Product.java
│ │ ├── mapper/ UserMapper.java, OrderMapper.java, ProductMapper.java
│ │ └── service/ UserService.java, OrderService.java
│ └── resources
│ ├── application.yml
│ ├── mybatis-config.xml (non-Spring setups only)
│ ├── schema.sql / data.sql
│ └── com/bitsnippets/shop/mapper/ UserMapper.xml, OrderMapper.xml
└── test
└── java/com/bitsnippets/shop/mapper/UserMapperTest.java
Interfaces are named XxxMapper, XML namespaces always equal the fully
qualified interface name, statement ids match method names, and every SQL keyword is
upper-case. These are not MyBatis requirements — they are the conventions that keep a
large mapper layer navigable, and chapter 14 explains why.
Versions this course targets
| Component | Version | Note |
|---|---|---|
| MyBatis core | 3.5.16 | Anything 3.5.x behaves identically for this material |
| mybatis-spring | 3.0.x | Required for Spring Framework 6 / Boot 3 |
| mybatis-spring-boot-starter | 3.0.x | Use 2.3.x if you are still on Boot 2.7 |
| JDK | 17 (21 also fine) | Records and var are used sparingly |
| Database | H2 2.x, MySQL 8, PostgreSQL 15 | Dialect differences are called out where they matter |