SpringBoot integrates Mybatis advanced usage

outline

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

Summary

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-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

Introducing database connection dependencies

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

Configure application.yml

Configure database connection in application.xml

spring:
  datasource:
    druid:
      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

Summary

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-->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.1.5</version>
</dependency>

Configure application.yml

Configure myBatis

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

Summary

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

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.10</version>
</dependency>

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;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootMybatisPlusApplication.class)
@Transactional
@Rollback
public class SpringbootMybatisPlusApplicationTests {

    @Autowired
    private TbItemMapper tbItemMapper;
    
    /**
     * Test Paging Query
     */
    @Test
    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) {
            System.out.println(tbItem.getTitle());
        }
    }
}

Generate code using Mybatis Maven plug-in

Summary

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

<build>
    <plugins>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.5</version>
            <configuration>
                <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                <overwrite>true</overwrite>
                <verbose>true</verbose>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>${mysql.version}</version>
                </dependency>
                <dependency>
                    <groupId>tk.mybatis</groupId>
                    <artifactId>mapper</artifactId>
                    <version>3.4.4</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>
  • 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"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!-- 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"/>
        </plugin>

        <!-- Configure database connection -->
        <jdbcConnection
                driverClass="${jdbc.driverClass}"
                connectionURL="${jdbc.connectionURL}"
                userId="${jdbc.username}"
                password="${jdbc.password}">
        </jdbcConnection>

        <!-- 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 -->
        <javaClientGenerator
                targetPackage="com.springboot.mybatisplus.mapper"
                targetProject="src/main/java"
                type="XMLMAPPER"/>

        <!-- 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"/>
        </table>
    </context>
</generatorConfiguration>

Configuring data sources

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

# MySQL 8.x: com.mysql.cj.jdbc.Driver
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://ip:port/dbname?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456

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