How to Integrate MyBatis with Spring Boot for CRUD Operations

This guide walks through integrating MyBatis into a Spring Boot project, covering dependency setup, MySQL configuration, entity and mapper creation, CRUD annotations, and unit testing to verify database operations, including transaction management and result mapping.

Programmer DD
Programmer DD
Programmer DD
How to Integrate MyBatis with Spring Boot for CRUD Operations

Previously we introduced two ways to access relational databases in Spring Boot: spring-boot-starter-jdbc and spring-boot-starter-data-jpa. This article demonstrates how to integrate MyBatis to perform CRUD operations.

Integrating MyBatis

Step 1: Add MyBatis starter and MySQL connector dependencies to pom.xml:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

Version 2.1.x supports MyBatis 3.5+, Java 8+, Spring Boot 2.1+. Versions 2.0.x and 1.3.x support older Spring Boot releases.

Step 2: Configure MySQL connection in application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

You may also use Druid as the connection pool if desired.

Step 3: Create a test table in MySQL, e.g., User with columns id (BIGINT), name (VARCHAR), and age (INT):

CREATE TABLE `User` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `name` varchar(100) COLLATE utf8mb4_general_ci DEFAULT NULL,
  `age` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

Step 4: Define the User entity:

@Data
@NoArgsConstructor
public class User {
    private Long id;
    private String name;
    private Integer age;
    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

Step 5: Create the mapper interface UserMapper with insert and select methods:

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM USER WHERE NAME = #{name}")
    User findByName(@Param("name") String name);

    @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);
}

Step 6: Add the Spring Boot main class:

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

Step 7: Write a unit test to verify CRUD operations:

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class Chapter35ApplicationTests {
    @Autowired
    private UserMapper userMapper;

    @Test
    @Rollback
    public void test() throws Exception {
        userMapper.insert("AAA", 20);
        User u = userMapper.findByName("AAA");
        Assert.assertEquals(20, u.getAge().intValue());
    }
}

Annotation Usage

MyBatis provides several ways to pass parameters:

@Param: Directly map method parameters to SQL placeholders.

Map: Use a Map<String, Object> where keys correspond to placeholders.

Object: Pass a POJO (e.g., User) and MyBatis binds its fields.

Typical CRUD annotations include @Select, @Insert, @Update, and @Delete. Example interface covering all four:

public interface UserMapper {
    @Select("SELECT * FROM user WHERE name = #{name}")
    User findByName(@Param("name") String name);

    @Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);

    @Update("UPDATE user SET age=#{age} WHERE name=#{name}")
    void update(User user);

    @Delete("DELETE FROM user WHERE id =#{id}")
    void delete(Long id);
}

Result mapping can be customized with @Results and @Result when the returned fields differ from the entity:

@Results({
    @Result(property = "name", column = "name"),
    @Result(property = "age", column = "age")
})
@Select("SELECT name, age FROM user")
List<User> findAll();

The above configuration intentionally omits the id column, which can be verified in a unit test.

For more advanced MyBatis usage, refer to the official documentation or the next article on XML‑based SQL configuration.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Javaunit testingSpring BootmysqlMyBatisCRUD
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.