Configuring MyBatis with XML Mappings in Spring Boot

Maven Dependencies

To integrate MyBatis with XML configuration, the necessary dependencies must be included in the pom.xml file. This typically involves adding the MyBatis Spring Boot Starter and the MySQL connector, similar to the annotation-based approach.

Defining the Entity

The data model remains consistent. A standard Java POJO is used to represent the database table structure. For instance, a User class with fields such as id, name, age, and sex serves as the entity.

Mapper Interface

Unlike the annotation-driven method where SQL statements are defined directly in the interface, the XML approach requires the interface to be a clean definition of data access methods without implementation details.
package com.example.repository;

import com.example.domain.User;
import java.util.List;

public interface UserRepository {

    List<User> findAll();

    User findById(Integer id);

    void add(User entity);

    void modify(User entity);

    void remove(Integer id);
}

Enabling Mapper Scanning

To ensure Spring Boot detects the mapper interfaces, the @MapperScan annotation is applied to the main application class, specifying the base package containing the interfaces.
package com.example.app;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.repository")
public class ApplicationInitializer {

    public static void main(String[] args) {
        SpringApplication.run(ApplicationInitializer.class, args);
    }
}

Controller Implementation

The controller handles HTTP requests and delegates the persistence logic to the mapper interface.
package com.example.controller;

import com.example.domain.User;
import com.example.domain.UserGender;
import com.example.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/list")
    public String listUsers(Model model) {
        List<User> users = userRepository.findAll();
        model.addAttribute("userList", users);
        return "listView";
    }

    @GetMapping("/add")
    public String addNewUser(Model model) {
        User newUser = new User();
        newUser.setName("John Doe");
        newUser.setAge(30);
        newUser.setSex(UserGender.MALE);
        
        userRepository.add(newUser);
        
        List<User> users = userRepository.findAll();
        model.addAttribute("userList", users);
        return "listView";
    }
}

Data Source Configuration

Proper database connectivity requires configuring the driver, URL, credentials, and connection settings in application.properties. It is advisable to specify character encoding and time zones explicitly to avoid common connection errors.
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot_db?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=admin123

XML Mapper Configuration

The core of the XML approach lies in the mapper XML files, which define the SQL statements and result mappings. These files are typically stored in the resources directory.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.repository.UserRepository">

    <resultMap id="UserResultMap" type="com.example.domain.User">
        <id column="user_id" property="id" jdbcType="INTEGER" />
        <result column="user_name" property="Name" jdbcType="VARCHAR" />
        <result column="user_age" property="Age" jdbcType="INTEGER" />
        <result column="user_sex" property="Sex" javaType="com.example.domain.UserGender" />
    </resultMap>

    <sql id="BaseColumns">
        user_id, user_name, user_age, user_sex
    </sql>

    <select id="findAll" resultMap="UserResultMap">
        SELECT 
        <include refid="BaseColumns" />
        FROM users
    </select>

    <select id="findById" parameterType="java.lang.Integer" resultMap="UserResultMap">
        SELECT 
        <include refid="BaseColumns" />
        FROM users
        WHERE user_id = #{id}
    </select>

    <insert id="add" parameterType="com.example.domain.User" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO users (user_name, user_age, user_sex)
        VALUES (#{Name}, #{Age}, #{Sex})
    </insert>

    <update id="modify" parameterType="com.example.domain.User">
        UPDATE users
        <set>
            <if test="Name != null">user_name = #{Name},</if>
            <if test="Age != null">user_age = #{Age},</if>
            <if test="Sex != null">user_sex = #{Sex}</if>
        </set>
        WHERE user_id = #{id}
    </update>

    <delete id="remove" parameterType="java.lang.Integer">
        DELETE FROM users
        WHERE user_id = #{id}
    </delete>

</mapper>

MyBatis Global Configuration

A central mybatis-config.xml can be created to define type aliases and other global settings, keeping the XML mappers cleaner.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <typeAliases>
        <typeAlias type="java.lang.Integer" alias="Integer" />
        <typeAlias type="java.util.List" alias="List" />
        <typeAlias type="java.util.Map" alias="Map" />
    </typeAliases>
</configuration>

Integration Properties

Finally, the locations of the mapper XML files and the global configuration file must be specified in application.properties to complete the integration.
mybatis.type-aliases-package=com.example.domain
mybatis.config-location=classpath:config/mybatis-config.xml
mybatis.mapper-locations=classpath:mapper/*.xml

Verification

Accessing the defined endpoints, such as /users/list or /users/add, should render the view and reflect the database operations, confirming that the XML configuration is correctly mapped to the interfaces.

Tags: Spring Boot MyBatis java XML Configuration database integration

Posted on Sun, 11 Oct 2026 16:05:45 +0000 by Soccerplayer1316