About the configuration and use of MyBatis

About the configuration and use of MyBatis

Although Spring Data JPA is widely popular abroad, MyBatis is still more commonly used in China

Integrate MyBatis

Step 1: Create a new Spring Boot project and introduce the MyBatis Starter and MySQL Connector dependencies in pom.xml, as follows:



Note about the version of mybatis-spring-boot-starter:

  • Version 2.1.x for: MyBatis 3.5+, Java 8+, Spring Boot 2.1+
  • Version 2.0.x is available for: MyBatis 3.5+, Java 8+, Spring Boot 2.0/2.1
  • Version 1.3.x is available for: MyBatis 3.4+, Java 6+, Spring Boot 1.5

Among them, the 2.1.x version and the 1.3.x version are still being maintained.

Step 2: Configure the connection configuration of mysql in application.properties as described before using the jdbc module and the jpa module to connect to the database


Of course, you can also not use the default data source (HikariCP). If you want to use Druid as the database connection pool, you can refer to "Spring Boot 2.x: Using Domestic Database Connection Pool Druid" one article.

Step 3: Create a table for testing in Mysql, such as the User table, which contains id(BIGINT), age(INT), and name(VARCHAR) fields.

The specific creation command is as follows:

  `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: Create the mapping object User of the User table:

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 operation interface of the User table: UserMapper. Define two data operations in the interface, one insert and one query, for subsequent unit test verification.

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: Create the Spring Boot main class

public class Chapter35Application {

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


Annotation configuration instructions

Let's use several different ways to pass parameters to implement the insertion operation implemented in the previous article, and learn some annotations commonly used in MyBatis.

Use @Param

In the previous integration example, we have used this simplest way of passing parameters, as follows:

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

This method is easy to understand. The name defined in @Param corresponds to #{name} in SQL, and age corresponds to #{age} in SQL.

Use Map

The following code uses a Map<String, Object> object as a container for passing parameters:

@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})")
int insertByMap(Map<String, Object> map);

For the parameters required in the Insert statement, we only need to fill in the content of the same name in the map, as shown in the following code:

Map<String, Object> map = new HashMap<>();
map.put("name", "CCC");
map.put("age", 40);

user target audience

In addition to Map objects, we can also directly use ordinary Java objects as parameters for query conditions. For example, we can directly use User objects:

@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
int insertByUser(User user);

In this way, #{name} and #{age} in the statement correspond to the name and age properties in the User object, respectively.


MyBatis provides different annotations for configuration for different database operations. In the previous example, @Insert is demonstrated. The following is an example of a set of basic additions, deletions, and changes for the User table:

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);

return result binding

Relatively small changes are made to addition, deletion, and modification operations. For the "check" operation, we often need to perform operations such as multi-table association, summary calculation, etc., then the result of the query is often no longer a simple entity object, and often needs to return a wrapper class that is different from the database entity. In this case, you can use the @Results and @Result annotations to bind, as follows:

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

XML format configuration description

Step 1: Add mapper's scan package configuration to the main application class:

public class Chapter36Application {

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


Step 2: Create the Mapper definition of the User table under the Mapper package specified in the first step:

public interface UserMapper {

    User findByName(@Param("name") String name);

    int insert(@Param("name") String name, @Param("age") Integer age);


Step 3: Specify the location of the xml configuration through the mybatis.mapper-locations parameter in the configuration file:


Step 4: Create the mapper configuration of the User table in the xml configuration directory specified in the third step:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<mapper namespace="com.didispace.chapter36.mapper.UserMapper">
    <select id="findByName" resultType="com.didispace.chapter36.entity.User">
        SELECT * FROM USER WHERE NAME = #{name}

    <insert id="insert">
        INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})

Here, the usage of MyBatis in the annotation mode has been changed to the configuration mode of XML.

Posted by alex_bg on Tue, 20 Sep 2022 21:53:06 +0530