Chapter 01

What is MyBatis, and why would you use it?

MyBatis is a persistence framework that maps SQL statements to Java methods. You write the SQL; MyBatis handles parameters, result mapping, caching and resource management. That one sentence explains almost every design decision in the library.

⏱ 12 min readLevel: beginnerUpdated for MyBatis 3.5.16

The problem MyBatis solves

Here is a plain JDBC method that loads one user. It is correct, it has no framework dependencies, and almost every line of it is ceremony:

UserJdbcDao.java — the "before" picture
public User findById(Long id) {
    String sql = "SELECT id, user_name, email, status FROM app_user WHERE id = ?";
    try (Connection cn = dataSource.getConnection();
         PreparedStatement ps = cn.prepareStatement(sql)) {

        ps.setLong(1, id);
        try (ResultSet rs = ps.executeQuery()) {
            if (!rs.next()) {
                return null;
            }
            User user = new User();
            user.setId(rs.getLong("id"));
            user.setUserName(rs.getString("user_name"));
            user.setEmail(rs.getString("email"));
            user.setStatus(UserStatus.valueOf(rs.getString("status")));
            return user;
        }
    } catch (SQLException e) {
        throw new DataAccessException("Failed to load user " + id, e);
    }
}

Nineteen lines, of which exactly one — the SELECT — carries business meaning. Multiply that by forty queries and you have a data-access layer where every change is a copy-paste risk. Worse, the column-to-field wiring is invisible to the compiler: rename a column and you find out at runtime, in production, on a Friday.

The same operation in MyBatis is a method signature and a query:

UserMapper.java
public interface UserMapper {
    User findById(Long id);
}
UserMapper.xml
<mapper namespace="com.bitsnippets.shop.mapper.UserMapper">
  <select id="findById" resultType="User">
    SELECT id, user_name, email, status
    FROM app_user
    WHERE id = #{id}
  </select>
</mapper>
UserService.java
User user = userMapper.findById(42L);

There is no implementation class. MyBatis creates a dynamic proxy for the interface, finds the statement whose id matches the method name inside the namespace that matches the interface name, binds the parameter, runs the query and maps the row. The SQL is still right there in front of you — that is the entire point.

Definition

MyBatis is a SQL mapper (sometimes called a data mapper), not an object-relational mapper. It maps statements to methods and result sets to objects. It never generates SQL from your object model, and it has no notion of a persistence context, dirty checking or automatic flushing.

A short history

MyBatis started life in 2002 as iBATIS, created by Clinton Begin. It became an Apache Software Foundation project, and in 2010 the team moved it to Google Code and renamed it MyBatis; development now lives on GitHub under the mybatis organisation. The 3.x line brought annotation-based mappers, the dynamic SQL engine built on OGNL, and the mapper-interface binding that makes the framework feel type-safe.

If you find a tutorial that talks about SqlMapClient or sqlmap-config.xml, you are reading iBATIS 2 material — the concepts rhyme, but the APIs are gone.

How MyBatis executes a statement

Understanding the runtime pipeline pays for itself the first time you have to debug a mapping problem. There are only six moving parts worth remembering.

Layered architecture diagram: application layer with mappers, bootstrap layer with SqlSessionFactory, core engine with SqlSession, Executor, StatementHandler and ResultSetHandler, and the JDBC layer
The four layers of a MyBatis application and the components inside the core engine.
ComponentResponsibilityYou touch it when…
SqlSessionFactoryBuilder Parses mybatis-config.xml into a Configuration object and builds a factory. Bootstrapping a non-Spring application.
SqlSessionFactory Immutable, thread-safe factory that hands out sessions. One per data source, for the life of the app. Application startup only.
SqlSession The unit of work: holds a connection, a transaction and the first level cache. Not thread-safe. Every request, in a try-with-resources block.
Executor Decides how a statement runs — SIMPLE, REUSE or BATCH — and performs cache lookups. Bulk inserts and cache tuning (chapters 6 and 9).
StatementHandler + ParameterHandler Creates the PreparedStatement and binds parameters via TypeHandlers. Writing a custom type handler (chapter 12).
ResultSetHandler Turns rows into objects using the declared resultType or resultMap. Mapping joins into object graphs (chapter 8).

The path of a single query

  1. Method callYou invoke userMapper.findById(42L) on a proxy.
  2. Statement lookupMyBatis resolves com…UserMapper.findById to a MappedStatement in the Configuration.
  3. Cache checkThe executor checks the second level cache, then the session's local cache. A hit ends the story here.
  4. SQL assemblyDynamic SQL nodes are evaluated against the parameter, producing a BoundSql: final SQL text plus an ordered list of parameter mappings.
  5. ExecutionA PreparedStatement is created, parameters are bound with type handlers, and JDBC runs the query.
  6. MappingThe result set handler builds objects, de-duplicating rows by <id> when nested mappings are involved.
  7. Cache storeThe result is written to the local cache (and to the namespace cache if enabled) and returned.

MyBatis vs Hibernate vs plain JDBC

This is the comparison that decides most projects, so let us be concrete rather than tribal.

Abstraction ladder showing plain JDBC, MyBatis and Hibernate with their trade-offs
MyBatis deliberately sits in the middle: it removes the boilerplate, not the SQL.
Plain JDBCMyBatisHibernate / JPA
Who writes the SQLYouYouThe framework (mostly)
Result mappingManualDeclarativeAutomatic from entity metadata
Learning curveLowLowHigh
Vendor-specific SQLTrivialTrivialNative queries, awkward
Stored proceduresNativeFirst-classPossible, clumsy
Schema generationNoneNoneBuilt in
Dirty checking / auto-updateNoneNoneYes
CachingNoneTwo levels, opt-inTwo levels plus query cache
Surprise queries at runtimeNeverNeverCommon (lazy loading, cascades)
Best fitOne-off toolsReport-heavy, legacy schemas, tuned SQLGreen-field domain models, heavy CRUD

A decision rule that actually works

Ask who owns the schema. If your application owns it and the model is mostly object-graph CRUD, Hibernate's automation is a genuine win. If the schema is owned by someone else — a legacy system, a DBA team, a reporting warehouse — or if your queries are the interesting part of the product (aggregations, window functions, vendor-specific features), MyBatis will save you weeks of fighting an abstraction.

It is not either/or

Plenty of production systems run JPA for the transactional entity graph and MyBatis for reporting and bulk operations, against the same data source. Both can enlist in the same Spring transaction. Chapter 11 shows the wiring.

What MyBatis is genuinely good at

  • Complex, hand-tuned SQL. CTEs, window functions, hints, MERGE, recursive queries — if JDBC can run it, MyBatis can map it.
  • Legacy schemas. Columns named USR_FLG_1, composite keys, tables you may not alter: a resultMap absorbs all of it without polluting your domain classes.
  • Dynamic queries. Search screens with twelve optional filters are a natural fit for the <where>/<if> engine, and the result is still parameterised and injection-safe.
  • Predictable performance. One mapper method means one statement. There is no lazy proxy that quietly fires 400 queries while you iterate a list.
  • Reviewable SQL. A DBA can read your mapper XML without knowing Java.
  • Small footprint. The core jar is around 1.7 MB with a single hard dependency-free runtime; startup cost is negligible.

Where MyBatis will not help you

  • No schema management. Bring Flyway or Liquibase; MyBatis will never create a table for you.
  • No automatic change tracking. Modifying a returned object does nothing. You call update explicitly — which is a feature until you forget.
  • Portability is your job. Write LIMIT and you are on MySQL/Postgres; Oracle 11 needs a different pagination idiom. MyBatis offers databaseId to branch, but nothing writes the dialects for you.
  • Refactoring is weaker. Renaming a column means grepping XML. Good naming and chapter 13's tests compensate; nothing eliminates it.
  • XML fatigue is real if you never adopt fragments and conventions. Chapter 14 covers keeping it tidy.

The mental model to carry forward

Keep three sentences in your head for the rest of the course and most MyBatis behaviour becomes predictable:

  1. A mapper interface method is just a lookup key for a SQL statement.
  2. A SqlSession is one connection, one transaction and one local cache — created late, closed early.
  3. Everything else — dynamic SQL, result maps, caches, plugins — is a transformation applied on the way in or on the way out.

Quick check: which statement about MyBatis is false?

MyBatis has no persistence context and no dirty checking. If you change an object you loaded, nothing happens until you call an update statement yourself. That explicitness is the trade you make for full control over SQL.

What is next

Chapter 2 gets a project running: dependencies, the sample schema, a SqlSessionFactory built by hand, and your first working query — no Spring involved, so you can see exactly what the framework does before any auto-configuration hides it.