SpringBoot integrates Mybatis advanced usage


This article focuses on SpringBoot's quick development tips for integrating Mybatis, which will enable us to achieve the rapid development effect of writing as few or as few SQL statements as possible or preferably no SQL statements when developing projects.

SpringBoot integrates Druid

SpringBoot integrates tk. mybatis (encapsulated with Mybatis)

SpringBook Integration PageHelper

Generate code using Mybatis Maven plug-in

SpringBoot integrates Druid


Druid is a project on Alibaba Open Source Platform. The whole project consists of database connection pool, plug-in framework and SQL parser. The main purpose of this project is to extend some limitations of JDBC. Programmers can realize some special requirements, such as requesting credentials from key service, statistical SQL information, SQL performance collection, SQL injection checking, SQL translation, etc. Programmers can customize to achieve the functions they need.

Druid is the best database connection pool at present. It surpasses other database connection pools in terms of function, performance and scalability, including DBCP, C3P0, BoneCP, Proxool and JBoss Data Source. Druid has deployed more than 600 applications in Alibaba, after years of rigorous deployment of large-scale production environment. Druid is a database connection pool developed by Alibaba called monitoring.

Introducing dependencies

Introducing druid-spring-boot-starter dependencies into pom.xml files

<!--Druid Data source dependency-->

Introducing database connection dependencies


Configure application.yml

Configure database connection in application.xml

      url: jdbc:mysql://ip:port/dbname?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
      username: root
      password: 123456
      initial-size: 1
      min-idle: 1
      max-active: 20
      test-on-borrow: true
      driver-class-name: com.mysql.jdbc.Driver

SpringBoot integrates tk.mybatis


tk.mybatis is a MyBatis framework based on a number of tools to make development more efficient

Introducing dependencies

Introducing mapper-spring-boot-starter dependencies in pom.xml files automatically introduces MyBaits dependencies

<!--tk.mybatis Dependence-->

Configure application.yml

Configure myBatis

    type-aliases-package: Storage paths of entity classes, such as: com.springboot.mybatisplus.entity
    mapper-locations: classpath:mapper/*.xml

Create a generic parent interface

The main function is to let the interface of DAO layer inherit this interface to achieve the purpose of using tk.mybatis.

import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

 * My own Mapper
 * In particular, the interface cannot be scanned, otherwise it will be wrong.
 * <p>Title: MyMapper</p>
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {

SpringBoot integrates PageHelper


PageHelper is Mybatis paging plug-in that supports multiple databases and data sources. It can simplify the paging query operation of the database, and the integration process is extremely simple, just by introducing dependencies.

Introducing dependencies

Introducing pagehelper-spring-boot-starter dependencies into pom.xml files


Here I do a simple test in the test class. The code is as follows:

package com.springboot.mybatisplus;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.springboot.mybatisplus.entity.TbItem;
import com.springboot.mybatisplus.entity.TbUser;
import com.springboot.mybatisplus.mapper.TbItemMapper;
import com.springboot.mybatisplus.mapper.TbUserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@SpringBootTest(classes = SpringbootMybatisPlusApplication.class)
public class SpringbootMybatisPlusApplicationTests {

    private TbItemMapper tbItemMapper;
     * Test Paging Query
    public void testPage() {
        // PageHelper is very simple to use, just set the page number and the number of bars per page.
        PageHelper.startPage(1, 10);

        // Setting Paging Query Conditions
        Example example = new Example(TbItem.class);
        PageInfo<TbItem> pageInfo = new PageInfo<>(tbItemMapper.selectByExample(example));

        // Get query results
        List<TbItem> tbItems = pageInfo.getList();
        for (TbItem tbItem : tbItems) {

Generate code using Mybatis Maven plug-in


We don't need to write entity class, DAO, XML configuration file manually. We just need to use a Maven plug-in provided by MyBatis to automatically generate all kinds of files needed to meet the basic business needs. If the business is complex, we only need to modify the relevant files.

Configuration plug-in

Add mybatis-generator-maven-plugin plug-in to the pom.xml file

  • Configuration File: Automatically generate the required configuration file path

Auto-generated configuration

Create the generatorConfig.xml configuration file in the src/main/resources/generator/directory:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"

    <!-- Introducing database connection configuration -->
    <properties resource="jdbc.properties"/>

    <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <!-- To configure tk.mybatis Plug-in unit -->
        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="tk.mybatis.MyMapper"/>

        <!-- Configure database connection -->

        <!-- Configure Entity Class Storage Path -->
        <javaModelGenerator targetPackage="com.springboot.mybatisplus.entity" targetProject="src/main/java"/>

        <!-- To configure XML Storage path -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>

        <!-- To configure DAO Storage path -->

        <!-- Configuration requires specifying the generated database and tables.% Represents all tables -->
        <table catalog="myshop" tableName="%">
            <!-- mysql To configure -->
            <generatedKey column="id" sqlStatement="Mysql" identity="true"/>

Configuring data sources

Create jdbc.properties data source configuration under src/main/resources directory:

# MySQL 8.x: com.mysql.cj.jdbc.Driver

After all the preparations are completed, click on the right-most Maven Icon

Success will be displayed in the console

At the same time, the generated code is displayed in the left directory bar.

Keywords: Mybatis JDBC SpringBoot MySQL

Added by Hobgoblin11 on Wed, 21 Aug 2019 16:36:35 +0300