Chapter 02

Installation, project setup and your first query

We will build a bare MyBatis application with no Spring, no auto-configuration and no magic. Twenty minutes from here you will have a running query and, more importantly, you will know which object created which.

⏱ 15 min readLevel: beginnerHands-on

Prerequisites

  • JDK 17 or newer on the path (java -version).
  • Maven 3.9+ or Gradle 8+.
  • A database. We use in-memory H2 so nothing has to be installed; MySQL and PostgreSQL coordinates are shown too.

Adding the dependencies

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.bitsnippets</groupId>
  <artifactId>mybatis-demo</artifactId>
  <version>1.0.0</version>

  <properties>
    <maven.compiler.release>17</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.16</version>
    </dependency>

    <!-- in-memory database for the samples -->
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <version>2.2.224</version>
    </dependency>

    <!-- optional but strongly recommended: see the SQL MyBatis runs -->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.5.6</version>
    </dependency>

    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>5.10.2</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>
build.gradle.kts
plugins {
    java
}

java {
    toolchain { languageVersion = JavaLanguageVersion.of(17) }
}

repositories { mavenCentral() }

dependencies {
    implementation("org.mybatis:mybatis:3.5.16")
    runtimeOnly("com.h2database:h2:2.2.224")
    implementation("ch.qos.logback:logback-classic:1.5.6")
    testImplementation("org.junit.jupiter:junit-jupiter:5.10.2")
}

tasks.test { useJUnitPlatform() }
driver coordinates
<!-- MySQL 8 -->
<dependency>
  <groupId>com.mysql</groupId>
  <artifactId>mysql-connector-j</artifactId>
  <version>8.4.0</version>
</dependency>

<!-- PostgreSQL -->
<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <version>42.7.3</version>
</dependency>

<!-- Oracle -->
<dependency>
  <groupId>com.oracle.database.jdbc</groupId>
  <artifactId>ojdbc11</artifactId>
  <version>23.4.0.24.05</version>
</dependency>
Only one required dependency

MyBatis core has no mandatory third-party dependency at runtime. Logging adapters, connection pools and cache providers are all optional and discovered reflectively — which is why the jar is small and startup is instant.

Creating the schema

Put these two files on the classpath. H2 can run them automatically through the JDBC URL, which keeps the sample self-contained.

src/main/resources/schema.sql
DROP TABLE IF EXISTS app_user;

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
);
src/main/resources/data.sql
INSERT INTO app_user (user_name, email, status) VALUES
    ('jerin',  'jerin@example.com',  'ACTIVE'),
    ('asha',   'asha@example.com',   'ACTIVE'),
    ('vikram', 'vikram@example.com', 'SUSPENDED');

The domain class

A plain POJO with a no-argument constructor and standard accessors. MyBatis needs the default constructor unless you declare constructor mapping (chapter 8).

com/bitsnippets/shop/domain/User.java
package com.bitsnippets.shop.domain;

import java.time.LocalDateTime;

public class User {

    private Long id;
    private String userName;
    private String email;
    private String status;
    private LocalDateTime createdAt;
    private int version;

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getUserName() { return userName; }
    public void setUserName(String userName) { this.userName = userName; }

    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }

    public String getStatus() { return status; }
    public void setStatus(String status) { this.status = status; }

    public LocalDateTime getCreatedAt() { return createdAt; }
    public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }

    public int getVersion() { return version; }
    public void setVersion(int version) { this.version = version; }

    @Override
    public String toString() {
        return "User{" + id + ", " + userName + ", " + email + ", " + status + "}";
    }
}

The configuration file

mybatis-config.xml is the root of a non-Spring setup. Chapter 3 dissects every element; for now, four blocks matter: settings, type aliases, the environment (transaction manager plus data source) and the mapper list.

src/main/resources/mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

  <settings>
    <!-- user_name -> userName, no resultMap needed -->
    <setting name="mapUnderscoreToCamelCase" value="true"/>
    <setting name="logImpl" value="SLF4J"/>
    <setting name="defaultStatementTimeout" value="30"/>
  </settings>

  <typeAliases>
    <package name="com.bitsnippets.shop.domain"/>
  </typeAliases>

  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="org.h2.Driver"/>
        <property name="url"
                  value="jdbc:h2:mem:shop;INIT=RUNSCRIPT FROM 'classpath:schema.sql'\;RUNSCRIPT FROM 'classpath:data.sql'"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
      </dataSource>
    </environment>
  </environments>

  <mappers>
    <mapper resource="com/bitsnippets/shop/mapper/UserMapper.xml"/>
  </mappers>

</configuration>
Element order is enforced

The config DTD requires a fixed order: properties, settings, typeAliases, typeHandlers, objectFactory, plugins, environments, databaseIdProvider, mappers. Put settings after typeAliases and startup fails with a parse error that does not explain itself.

The mapper interface and XML

Two rules connect them: the XML namespace must equal the fully qualified interface name, and each statement id must equal a method name.

com/bitsnippets/shop/mapper/UserMapper.java
package com.bitsnippets.shop.mapper;

import com.bitsnippets.shop.domain.User;
import java.util.List;

public interface UserMapper {

    User findById(Long id);

    List<User> findAll();

    List<User> findByStatus(String status);

    int insert(User user);
}
src/main/resources/com/bitsnippets/shop/mapper/UserMapper.xml
<?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.bitsnippets.shop.mapper.UserMapper">

  <sql id="userColumns">
    id, user_name, email, status, created_at, version
  </sql>

  <select id="findById" resultType="User">
    SELECT <include refid="userColumns"/>
    FROM app_user
    WHERE id = #{id}
  </select>

  <select id="findAll" resultType="User">
    SELECT <include refid="userColumns"/>
    FROM app_user
    ORDER BY id
  </select>

  <select id="findByStatus" resultType="User">
    SELECT <include refid="userColumns"/>
    FROM app_user
    WHERE status = #{status}
    ORDER BY user_name
  </select>

  <insert id="insert" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO app_user (user_name, email, status)
    VALUES (#{userName}, #{email}, #{status})
  </insert>

</mapper>
The number one setup mistake

Maven does not copy .xml files that live in src/main/java. If you prefer to keep the mapper XML beside its interface, add a resource include to the build, otherwise you will get Invalid bound statement (not found) at runtime while everything looks correct in your IDE.

pom.xml — build section
<build>
  <resources>
    <resource>
      <directory>src/main/java</directory>
      <includes><include>**/*.xml</include></includes>
    </resource>
    <resource><directory>src/main/resources</directory></resource>
  </resources>
</build>

Building the SqlSessionFactory

One factory per application. Building it parses the config and every mapper, so doing it per request is a classic performance bug.

com/bitsnippets/shop/MyBatisFactory.java
package com.bitsnippets.shop;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;

public final class MyBatisFactory {

    private static final SqlSessionFactory FACTORY = build();

    private MyBatisFactory() { }

    private static SqlSessionFactory build() {
        try (InputStream in = Resources.getResourceAsStream("mybatis-config.xml")) {
            return new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            throw new UncheckedIOException("Cannot read mybatis-config.xml", e);
        }
    }

    public static SqlSessionFactory get() {
        return FACTORY;
    }
}
Lifecycle diagram of SqlSessionFactoryBuilder, SqlSessionFactory, SqlSession and mapper scopes
Scope rules. Getting these wrong is responsible for most “connection leak” incidents.

Running your first query

com/bitsnippets/shop/DemoApp.java
package com.bitsnippets.shop;

import com.bitsnippets.shop.domain.User;
import com.bitsnippets.shop.mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class DemoApp {

    public static void main(String[] args) {

        try (SqlSession session = MyBatisFactory.get().openSession()) {

            UserMapper mapper = session.getMapper(UserMapper.class);

            User one = mapper.findById(1L);
            System.out.println("findById(1) -> " + one);

            List<User> active = mapper.findByStatus("ACTIVE");
            active.forEach(u -> System.out.println("active -> " + u));

            User created = new User();
            created.setUserName("neha");
            created.setEmail("neha@example.com");
            created.setStatus("ACTIVE");

            mapper.insert(created);
            session.commit();                       // without this, nothing is persisted

            System.out.println("generated id -> " + created.getId());
        }
    }
}
console output
findById(1) -> User{1, jerin, jerin@example.com, ACTIVE}
active -> User{1, jerin, jerin@example.com, ACTIVE}
active -> User{2, asha, asha@example.com, ACTIVE}
generated id -> 4

Turn on SQL logging immediately

Working blind is the fastest way to waste an afternoon. This configuration prints every statement and every bound parameter.

src/main/resources/logback.xml
<configuration>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder><pattern>%d{HH:mm:ss} %-5level %logger{28} - %msg%n</pattern></encoder>
  </appender>

  <!-- one logger per mapper namespace: DEBUG prints SQL, TRACE prints result rows -->
  <logger name="com.bitsnippets.shop.mapper" level="TRACE"/>

  <root level="INFO">
    <appender-ref ref="STDOUT"/>
  </root>
</configuration>
what you will see
10:14:02 DEBUG c.b.s.mapper.UserMapper.findById - ==>  Preparing: SELECT id, user_name, email, status, created_at, version FROM app_user WHERE id = ?
10:14:02 DEBUG c.b.s.mapper.UserMapper.findById - ==> Parameters: 1(Long)
10:14:02 TRACE c.b.s.mapper.UserMapper.findById - <==    Columns: ID, USER_NAME, EMAIL, STATUS, CREATED_AT, VERSION
10:14:02 TRACE c.b.s.mapper.UserMapper.findById - <==        Row: 1, jerin, jerin@example.com, ACTIVE, 2026-01-04 10:14:02.11, 0
10:14:02 DEBUG c.b.s.mapper.UserMapper.findById - <==      Total: 1

Troubleshooting the first run

SymptomCauseFix
Invalid bound statement (not found) XML not on the classpath, namespace typo, or statement id ≠ method name Check target/classes for the XML; compare namespace with the FQN character by character
There is no getter for property named 'x' #{x} does not match a property, or a multi-arg method lacks @Param Annotate parameters with @Param("x") (chapter 5)
All fields null except the id Snake-case columns and camelCase properties without mapping Enable mapUnderscoreToCamelCase or alias columns
Insert appears to work but the row is gone Missing session.commit() Commit explicitly, or open the session with autocommit (chapter 10)
Error building SqlSession … Cause: DTD Config elements in the wrong order, or the mapper DTD used in the config file Use the config DTD for mybatis-config.xml and keep the element order
Connections exhausted after some minutes Sessions never closed Always use try-with-resources

How many SqlSessionFactory instances should a single-database application create?

Building a factory parses the configuration and every mapper file. It is immutable and thread-safe afterwards, so build it once at startup and share it. Sessions, by contrast, are cheap and short-lived.

Next

You now have a working project. Chapter 3 goes through mybatis-config.xml element by element — including the settings that silently change behaviour, like callSettersOnNulls and defaultExecutorType.