Detailed steps for integrating Mybatis using SpringBoot

Posted by jschultz on Wed, 09 Mar 2022 09:20:09 +0100

Step 1: configure pom file, and configure mybatis and database related dependencies

Here, mybatis uses version 3.4.5. Note: mybatis 3 @ Mapper annotation is only supported for versions above 4.0

Relevant dependency codes are as follows:

<dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>

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

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

The complete code of pom file is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-demo1</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
        </dependency>
        <dependency>
            <groupId>org.xmlunit</groupId>
            <artifactId>xmlunit-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>7</source>
                    <target>7</target>
                </configuration>
            </plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>8</source><target>8</target></configuration></plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

After importing the pom file, if the dependency is red, you need to re import it (click the refresh icon in the figure below)

Step 2: create a new package in the project and add the following files under the corresponding package

The main packages designed here include controller (control layer), entity (entity layer), service (interface layer), serviceimpl (interface implementation layer) and mapper (data persistence layer)

Step 3: write entity classes and build corresponding tables in the database

Write the student Entity class under the Entity package. The code is as follows

package com.example.demo.Entity;


import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Data
public class Student {
    private String id;
    private String name;
    private Integer age;
    private String sex;
    private String grade;

    public Student(String id,String name,Integer age,String sex,String grade)
    {
        this.id = id;
        this.name=name;
        this.age=age;
        this.sex=sex;
        this.grade=grade;
    }
}

Create a new student table in the database:

Insert data into the table for subsequent interface verification

Step 4: in application Configure database and mybatis related properties in properties

Port refers to the port number, which can not be set (this setting is because port 8080 is occupied)

The name, account number and password of the database can be changed to your own

server.port=8081
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/stms?useUnicode=true&characterEncoding=UTF-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
mybatis.type-aliases-package=com.example.demo.Entity
mybatis.mapper-locations= classpath:com.example.demo.Mapper/*.xml

Step 5: add Mapper interface file and corresponding xml file

You can add @ MapperScan annotation on the startup class or @ MapperScan annotation on each interface class of Mapper layer. The function of @ maperscan annotation: specify the package where the interface to become the implementation class is located, and then all interfaces under the package will generate corresponding implementation classes after compilation

@MapperScan(basePackages = "com.example.demo.Mapper")

The studentMapper interface class code is as follows

package com.example.demo.Mapper;


import com.example.demo.Entity.Student;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface StudentMapper {
  List<Student> selectAll();
}

Create the following directories and files under resource

The complete code is as follows:

Note: the value of namespace should correspond to the path of the interface class, otherwise an error will be reported

<?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.demo.Mapper.StudentMapper">

    <select id="selectAll"  resultType="com.example.demo.Entity.Student">
        select id,name,age,sex,grade
        from `student`
    </select>


</mapper>

Step 6: write the Controller layer

Write the test code in the StudentController file of the Controller layer, as follows:

package com.example.demo.Controller;

import com.example.demo.DTO.ResultDto;
import com.example.demo.Entity.Student;
import com.example.demo.Mapper.StudentMapper;
import com.example.demo.Service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @Autowired
    private StudentMapper studentMapper;


    @GetMapping("/getAll")
    public String selectAll()
    {
        
        List<Student> students = studentMapper.selectAll();
        
        return students.toString();
    }
}

Last step: enter in the browser http://localhost:8081/student/getAll

If the following data appears, the integration is successful:

Write at the end: it's not easy to create. If the article here is helpful to you, you may wish to praise and support. Thank you very much!

Topics: Java Maven Spring Boot