SpringBoot combat (xiii) | integration of MyBatis (XML version)

  java, mybatis, mybatis-generator, springboot

WeChat Public Number: An Outstanding Disabled Person
If you have any questions or suggestions, please leave a message backstage. I will try my best to solve your problem.


For example, today I will introduce the integration of SpringBoot and Mybatis and the use of Mybatis. I have previously introduced the use of SpringBoot’s integrated MyBatis annotated version. The previous article introduced the theory of MyBatis. Today this article will not introduce the theory of MyBatis. I am interested in jumping to read:SpringBoot combat (xiii) | integration of MyBatis (annotated version)

Preparatory work

  • SpringBoot 2.1.3
  • IDEA
  • JDK 8

Create table

CREATE TABLE `student`  (
  `student_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '学号',
  `name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '姓名',
  `age` int(11) NULL DEFAULT NULL COMMENT '年龄',
  `city` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '所在城市',
  `dormitory` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '宿舍',
  `major` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '专业',

Introduce dependency

        <!-- jdbc 连接驱动 -->
        <!-- web 启动类 -->
        <!-- mybatis 依赖 -->
        <!-- druid 数据库连接池 -->
        <!-- Mysql 连接类 -->
        <!-- 分页插件 -->
        <!-- test 依赖 -->

            <!-- springboot maven 插件 -->
            <!-- mybatis generator 自动生成代码插件 -->

The code explanation is very detailed, but let’s mention here that the mybatis generator plug-in is used to automatically generate code and the pagehelper plug-in is used for physical paging.

Project configuration

  port: 8080

        name: test
        url: jdbc:mysql://
        username: root
        password: 123456
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20

## 该配置节点为独立的节点,有很多同学容易将这个配置放在spring的节点下,导致配置无法被识别
  mapper-locations: classpath:mapping/*.xml  #注意:一定要对应mapper映射xml文件的所在路径
  type-aliases-package: com.nasus.mybatisxml.model  # 注意:对应实体类的路径

    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql

Mybatis generator profile

It should be noted here that when configuring the configuration file corresponding to the generator plug-in in pom.xml, add this sentence in Pom.xml to explain the configuration file path corresponding to the configuration file corresponding to the generator plug-in. This is already configured in Pom, please see Pom configuration above.


generatorConfig.xml :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
    <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
    <classPathEntry  location="D:\repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar"/>
    <context id="DB2Tables"  targetRuntime="MyBatis3">
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        <!--数据库链接URL,用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://" userId="root" password="123456">
            <property name="forceBigDecimals" value="false"/>
        <!-- 生成模型的包名和位置-->
        <javaModelGenerator targetPackage="com.nasus.mybatisxml.model" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        <!-- 生成映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        <!-- 生成DAO的包名和位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.nasus.mybatisxml.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
        <table tableName="student" domainObjectName="Student" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>

The code comments are very detailed, not much said.

Code generation process

Step 1: Select Edit Configuration


Step 2: Select Add Maven Configuration

选择 Maven

Step 3: add the command mybatis-generator:generate -e-e click ok.


Step 4: Run the configuration to generate code

Pay special attention! ! ! The same table must not be run multiple times, because mapper’s mapping file will generate multiple codes, resulting in errors, remember. If you want to run it multiple times, please delete the mapper mapping file code generated last time and run it again.


Step 5: Check the generated results


Problems encountered

Please refer to other people’s written solutions to problems, among which I metThe database time zone is incorrectas well asOnly Insert methods are generatedThese two questions. All of them were solved by reading the following article:

Mybatis Generator automatically generates code and possible problems

Generated code

1. Entity Class: Student.java

package com.nasus.mybatisxml.model;

public class Student {

    private Long id;

    private Integer age;

    private String city;

    private String dormitory;

    private String major;

    private String name;

    private Long studentId;

   // 省略 get 和 set 方法

2. mapper Interface: StudentMapper.java

package com.nasus.mybatisxml.mapper;

import com.nasus.mybatisxml.model.Student;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;

public interface StudentMapper {
    int deleteByPrimaryKey(Long id);

    int insert(Student record);

    int insertSelective(Student record);

    Student selectByPrimaryKey(Long id);

    // 我添加的方法,相应的要在映射文件中添加此方法
    List<Student> selectStudents();

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);

3. mapping file: StudentMapper.xml

<?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.nasus.mybatisxml.mapper.StudentMapper" >
  <resultMap id="BaseResultMap" type="com.nasus.mybatisxml.model.Student" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="age" property="age" jdbcType="INTEGER" />
    <result column="city" property="city" jdbcType="VARCHAR" />
    <result column="dormitory" property="dormitory" jdbcType="VARCHAR" />
    <result column="major" property="major" jdbcType="VARCHAR" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="student_id" property="studentId" jdbcType="BIGINT" />

  <sql id="Base_Column_List" >
    id, age, city, dormitory, major, name, student_id

  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    <include refid="Base_Column_List" />
    from student
    where id = #{id,jdbcType=BIGINT}

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from student
    where id = #{id,jdbcType=BIGINT}

  <insert id="insert" parameterType="com.nasus.mybatisxml.model.Student" >
    insert into student (id, age, city, 
      dormitory, major, name, 
    values (#{id,jdbcType=BIGINT}, #{age,jdbcType=INTEGER}, #{city,jdbcType=VARCHAR}, 
      #{dormitory,jdbcType=VARCHAR}, #{major,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, 

  <insert id="insertSelective" parameterType="com.nasus.mybatisxml.model.Student" >
    insert into student
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
      <if test="age != null" >
      <if test="city != null" >
      <if test="dormitory != null" >
      <if test="major != null" >
      <if test="name != null" >
      <if test="studentId != null" >
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
      <if test="age != null" >
      <if test="city != null" >
      <if test="dormitory != null" >
      <if test="major != null" >
      <if test="name != null" >
      <if test="studentId != null" >

  <update id="updateByPrimaryKeySelective" parameterType="com.nasus.mybatisxml.model.Student" >
    update student
    <set >
      <if test="age != null" >
        age = #{age,jdbcType=INTEGER},
      <if test="city != null" >
        city = #{city,jdbcType=VARCHAR},
      <if test="dormitory != null" >
        dormitory = #{dormitory,jdbcType=VARCHAR},
      <if test="major != null" >
        major = #{major,jdbcType=VARCHAR},
      <if test="name != null" >
        name = #{name,jdbcType=VARCHAR},
      <if test="studentId != null" >
        student_id = #{studentId,jdbcType=BIGINT},
    where id = #{id,jdbcType=BIGINT}

  <update id="updateByPrimaryKey" parameterType="com.nasus.mybatisxml.model.Student" >
    update student
    set age = #{age,jdbcType=INTEGER},
      city = #{city,jdbcType=VARCHAR},
      dormitory = #{dormitory,jdbcType=VARCHAR},
      major = #{major,jdbcType=VARCHAR},
      name = #{name,jdbcType=VARCHAR},
      student_id = #{studentId,jdbcType=BIGINT}
    where id = #{id,jdbcType=BIGINT}

  <!-- 我添加的方法 -->
  <select id="selectStudents" resultMap="BaseResultMap">
    <include refid="Base_Column_List" />
    from student

Serviec layer

1. Interface:

public interface StudentService {

    int addStudent(Student student);

    Student findStudentById(Long id);

    PageInfo<Student> findAllStudent(int pageNum, int pageSize);


2. Implementation Class

public class StudentServiceImpl implements StudentService{

    private StudentMapper studentMapper;

     * 添加学生信息
     * @param student
     * @return
    public int addStudent(Student student) {
        return studentMapper.insert(student);

     * 根据 id 查询学生信息
     * @param id
     * @return
    public Student findStudentById(Long id) {
        return studentMapper.selectByPrimaryKey(id);

     * 查询所有学生信息并分页
     * @param pageNum
     * @param pageSize
     * @return
    public PageInfo<Student> findAllStudent(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Student> studentList = studentMapper.selectStudents();
        PageInfo result = new PageInfo(studentList);
        return result;

Controller layer

public class StudentController {

    private StudentService studentService;

    public Student findStidentById(@PathVariable("id") Long id){
        return studentService.findStudentById(id);

    public int insertStudent(@RequestBody Student student){
        return studentService.addStudent(student);

    public PageInfo<Student> findStudentList(@RequestParam(name = "pageNum", required = false, defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize", required = false, defaultValue = "10") int pageSize){
        return studentService.findAllStudent(pageNum,pageSize);

Starting class

@MapperScan("com.nasus.mybatisxml.mapper") // 扫描 mapper 接口,必须加上
public class MybatisxmlApplication {

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

By the way, the annotation @ mapperscan (“com.nasus.mybatisxml.mappe”) is very critical. this corresponds to the package path corresponding to mapper(dao) in the project. it must be added, otherwise it will cause an exception.

Postman test

1. Insert method:


2, according to the id query method:

根据 id 查询结果

3. Pagination inquiry method:


Source code download

https://github.com/turoDog/De …

Can you help me with a star?


If this article is of any help to you, please help me look good. Your good looks are my motivation to persist in writing.

In addition, attention is sent after1024Free study materials are available. For details of the information, please refer to this old article:Python, C++, Java, Linux, Go, Front End, Algorithm Data Sharing