Spring Boot and MyBatis: Run Mappers Against H2
MyBatis connects Java methods to SQL. Even with a working connection, mismatched parameter names or result columns can break inserts or leave fields empty. Use one employee table to compare annotation and XML mappers and check real inserts, queries, and deletes.
Start with a copy of the base project from lab setup. The baseline is Java 17 source, Spring Boot 3.5.16, and MyBatis Starter 3.0.4. The Starter 3.0 line targets Spring Boot 3.2 through 3.5. Do not mix it with the older 2.2 dependency line.
Dependencies and seed data
Section titled “Dependencies and seed data”The first block is a fragment to add inside dependencies in the base pom.xml. Save each remaining block at its titled path. The Maven resource directory is src/main/resources.
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>3.0.4</version></dependency><dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope></dependency>spring.datasource.url=jdbc:h2:mem:employees;DB_CLOSE_DELAY=-1spring.datasource.username=saspring.datasource.password=spring.sql.init.mode=alwaysmybatis.configuration.map-underscore-to-camel-case=truemybatis.mapper-locations=classpath*:mybatis/**/*.xmlCREATE TABLE employees ( emp_no BIGINT PRIMARY KEY, first_name VARCHAR(80) NOT NULL, hire_date DATE NOT NULL);INSERT INTO employees (emp_no, first_name, hire_date)VALUES (1, 'Alex', DATE '2026-01-01');H2 supports this exercise without an external database. schema.sql and data.sql are the default initialization filenames. spring.sql.init.mode=always runs initialization when the application starts. Production schema changes and data migrations need a separate strategy.
Java object for results
Section titled “Java object for results”package com.example.tutorial;
import java.time.LocalDate;
public class Employee { private long empNo; private String firstName; private LocalDate hireDate;
public Employee() {}
public Employee(long empNo, String firstName, LocalDate hireDate) { this.empNo = empNo; this.firstName = firstName; this.hireDate = hireDate; }
public long getEmpNo() { return empNo; } public void setEmpNo(long empNo) { this.empNo = empNo; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public LocalDate getHireDate() { return hireDate; } public void setHireDate(LocalDate hireDate) { this.hireDate = hireDate; }}The default constructor and setters allow MyBatis to populate results. map-underscore-to-camel-case=true maps first_name to firstName. Column and field names do not always have to match; explicit result mappings provide another option. LocalDate preserves the date-only meaning of SQL DATE.
Annotation mapper
Section titled “Annotation mapper”package com.example.tutorial;
import java.util.List;import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Mapper;import org.apache.ibatis.annotations.Param;import org.apache.ibatis.annotations.Select;
@Mapperpublic interface EmployeeMapper { @Select("SELECT emp_no, first_name, hire_date FROM employees ORDER BY emp_no") List<Employee> findAll();
@Select("SELECT emp_no, first_name, hire_date FROM employees WHERE emp_no = #{empNo}") Employee findById(@Param("empNo") long empNo);
@Insert("INSERT INTO employees (emp_no, first_name, hire_date) " + "VALUES (#{empNo}, #{firstName}, #{hireDate})") int save(Employee employee);
@Delete("DELETE FROM employees WHERE emp_no = #{empNo}") int deleteById(@Param("empNo") long empNo);}The Starter finds interfaces annotated with @Mapper and registers them as Spring beans. @Param("empNo") specifies the name used in SQL. The object parameter in save() exposes its properties for binding.
#{hireDate} is a prepared-statement parameter. Omitting its leading # prevents value binding. Do not concatenate user input into SQL strings. findById() returns null for a missing row, so the calling service must define its missing-item behavior.
XML mapper alternative
Section titled “XML mapper alternative”To keep SQL in a separate file, use the following interface and XML. Its distinct interface name allows it to coexist with the annotation mapper for comparison. Do not define the same statement for one interface in both annotations and XML.
package com.example.tutorial;
import org.apache.ibatis.annotations.Mapper;import org.apache.ibatis.annotations.Param;
@Mapperpublic interface EmployeeXmlMapper { Employee findById(@Param("empNo") long empNo); int save(Employee employee); int deleteById(@Param("empNo") long empNo);}<?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.example.tutorial.EmployeeXmlMapper"> <resultMap id="employee" type="com.example.tutorial.Employee"> <id column="emp_no" property="empNo"/> <result column="first_name" property="firstName"/> <result column="hire_date" property="hireDate"/> </resultMap> <select id="findById" resultMap="employee"> SELECT emp_no, first_name, hire_date FROM employees WHERE emp_no = #{empNo} </select> <insert id="save" parameterType="com.example.tutorial.Employee"> INSERT INTO employees (emp_no, first_name, hire_date) VALUES (#{empNo}, #{firstName}, #{hireDate}) </insert> <delete id="deleteById"> DELETE FROM employees WHERE emp_no = #{empNo} </delete></mapper>The namespace must match the fully qualified interface name, and a statement id must match its method name. This XML uses the full class name and an explicit resultMap, so no type alias registration is needed.
Check inserts, queries, and deletes
Section titled “Check inserts, queries, and deletes”package com.example.tutorial;
import java.time.LocalDate;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)@Transactionalclass EmployeeMapperTest { @Autowired EmployeeMapper mapper; @Autowired EmployeeXmlMapper xmlMapper;
@Test void readsSeedDataAndMapsColumnNames() { var employee = mapper.findById(1); assertThat(employee.getFirstName()).isEqualTo("Alex"); assertThat(employee.getHireDate()).isEqualTo(LocalDate.of(2026, 1, 1)); }
@Test void insertsAllParametersIncludingHireDate() { mapper.save(new Employee(2, "Sam", LocalDate.of(2026, 2, 1))); var employee = mapper.findById(2); assertThat(employee.getFirstName()).isEqualTo("Sam"); assertThat(employee.getHireDate()).isEqualTo(LocalDate.of(2026, 2, 1)); }
19 collapsed lines
@Test void deletesTheSelectedEmployee() { assertThat(mapper.deleteById(1)).isEqualTo(1); assertThat(mapper.findById(1)).isNull(); }
@Test void xmlMapperInsertsAndReadsTheSameColumns() { xmlMapper.save(new Employee(3, "Kim", LocalDate.of(2026, 3, 1))); var employee = xmlMapper.findById(3); assertThat(employee.getEmpNo()).isEqualTo(3); assertThat(employee.getFirstName()).isEqualTo("Kim"); assertThat(employee.getHireDate()).isEqualTo(LocalDate.of(2026, 3, 1)); }
@Test void xmlMapperDeletesTheSelectedEmployee() { assertThat(xmlMapper.deleteById(1)).isEqualTo(1); assertThat(xmlMapper.findById(1)).isNull(); }}mvn test -Dtest=EmployeeMapperTestCheck the seeded name and date, insert a new employee, and read back the same values. After deletion, querying the ID must return no row. Each test runs in a transaction that rolls back afterward, preserving seed data for the other tests.
Scope of this example
Section titled “Scope of this example”This configuration teaches mapper binding with one DataSource and H2. When moving to an external database, review its JDBC driver, SQL dialect, permissions, connection pool, and migrations. If multiple DataSources are needed, explicitly separate their session factories and mapper scan boundaries.