Course · 15 chapters

The Complete MyBatis Tutorial

MyBatis is the SQL mapping framework for developers who want the convenience of an ORM without giving up control of their SQL. This course takes you from an empty pom.xml to interceptor plugins, cache tuning and Testcontainers-backed integration tests — using one schema and one growing example project throughout.

MyBatis 3.5.x mybatis-spring-boot-starter 3.x Java 17+ Free · no sign-up
MyBatis architecture: application layer, configuration, core engine and JDBC layer

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.

Four-stage roadmap: foundations, mapping, depth, production
The course in four stages. Chapters 1–3 are prerequisites; after that you can jump around.

Syllabus

01

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.

02

Installation and project setup

Maven and Gradle coordinates, the H2/MySQL sample schema, building the SqlSessionFactory, and running your first query end to end.

03

The configuration file

Every element of mybatis-config.xml: properties, settings, type aliases, type handlers, environments, data sources and mapper registration.

04

Mapper XML in depth

select, insert, update, delete, reusable <sql> fragments, and the security-critical difference between #{} and ${}.

05

Annotation-based mappers

@Select, @Results, @Param, @Options, SQL providers and the SQL builder DSL — plus when XML is still the right call.

06

CRUD operations

A full create/read/update/delete implementation with generated keys, batch inserts, pagination and optimistic locking.

07

Dynamic SQL

if, choose, where, set, trim, foreach and bind — with the generated SQL shown for each branch.

08

ResultMaps, associations, collections

Turning joined rows into object graphs, nested results vs nested selects, discriminators, and how to detect and kill N+1 queries.

09

Caching

The session-local first level cache, the namespace second level cache, eviction policies, cache-ref, Redis, and when caching hurts.

10

Transactions and sessions

Session scope rules, commit/rollback semantics, isolation levels, executor types and batch flushing.

11

Spring Boot integration

The starter, application.yml properties, @MapperScan, SqlSessionTemplate, declarative transactions and multiple data sources.

12

Plugins, type handlers, generation

Writing interceptors, custom TypeHandlers for enums and JSON columns, stored procedures, and MyBatis Generator.

13

Testing your mappers

Fast H2 tests, realistic Testcontainers tests, the @MybatisTest slice, fixtures and asserting the SQL that actually ran.

14

Best practices and pitfalls

Naming, layout, mapper design rules, a performance checklist and the twelve mistakes behind most production incidents.

15

FAQ and interview questions

Forty questions with direct answers, plus a one-page cheat sheet you can keep open while you work.

Start

Begin 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.

schema.sql
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.

project tree
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
Conventions used in this course

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

ComponentVersionNote
MyBatis core3.5.16Anything 3.5.x behaves identically for this material
mybatis-spring3.0.xRequired for Spring Framework 6 / Boot 3
mybatis-spring-boot-starter3.0.xUse 2.3.x if you are still on Boot 2.7
JDK17 (21 also fine)Records and var are used sparingly
DatabaseH2 2.x, MySQL 8, PostgreSQL 15Dialect differences are called out where they matter