Integrated MybatisPlus

Import dependence

        <! --mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <! --mybatPlus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>Rule 3.4.3</version>
        </dependency>
        <! -- Generator dependency -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1 track</version>
        </dependency>
        <! --MyBatis -- Plus removed the default dependencies on code generators and template engines from 3.0.3, requiring manual addition of dependencies:
        <! MyBatis-Plus supports Velocity (default), Freemarker, Beetl, etc. You can choose a template engine that you are familiar with. If none of them meet your requirements, you can use a custom template engine. -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.31</version>
        </dependency>
        <! -- P6SPY -->
        <dependency>
            <groupId>p6spy</groupId>
            <artifactId>p6spy</artifactId>
            <version>3.9.0</version>
        </dependency>
Copy the code

Configuration file writing

#-------------------- Configure the data source ----------------#
#--------------- Database connection configuration --------------
Database connection pool
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
# username
spring.datasource.username=root
# your password
spring.datasource.password=root
P6sp = p6spspring.datasource.url=jdbc:p6spy:mysql://localhost:3306/blog? zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&autoReconnect=true
# drive name
# need to debug interception print SQL driver to p6SP interception
spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver
#--------------- Database connection pool HikariCP configuration --------------
# minimum free connection, default value 10, less than 0 or greater than maximum-pool-size, reset to maximum-pool-size
spring.datasource.hikari.minimum-idle=10
# maximum number of connections, less than or equal to 0 will be reset to the default value 10; If the value is greater than zero and less than 1, the value is reset to minimum-idle
spring.datasource.hikari.maximum-pool-size=20
# Idle connection timeout, default 600000 milliseconds (10 minutes),
If the value is greater than or equal to max-lifetime and max-lifetime>0, the value will be reset to 0. Not equal to 0 and less than 10 seconds will be reset to 10 seconds.
spring.datasource.hikari.idle-timeout=500000
Max connection lifetime, not equal to 0 and less than 30 seconds, will be reset to the default value of 30 minutes. The setting should be shorter than the timeout set by mysql
spring.datasource.hikari.max-lifetime=540000
# connection timeout: ms, less than 250 ms, otherwise reset to default 30 seconds
spring.datasource.hikari.connection-timeout=60000
A query statement used to test whether the connection is available
spring.datasource.hikari.connection-test-query=SELECT 1
# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- mybatisPlus configuration -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Mapper.xml file location
mybatis-plus.mapper-locations=classpath:mapper/*.xml
This property allows you to register aliases for classes in a package
mybatis-plus.type-aliases-package=cn.soboys.blogapi.entity
# Console prints the mybatisPlus LOGO
mybatis-plus.global-config.banner=true
Copy the code

Add the Mapper scan code

@SpringBootApplication(scanBasePackages = {"cn.soboys"})
@MapperScan({"cn.soboys.blogapi.mapper"})
public class BlogApiApplication {

    public static void main(String[] args) { SpringApplication.run(BlogApiApplication.class, args); }}Copy the code

CRUD code generation

Write code to generate template utility classes

package cn.soboys;


import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/ * * *@author kenx
 * @version 1.0
 * @date* Automatic code generator */
public class MyBatisGeneratorCode {
    /** * 

* read the console contents *

*/
public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append("Please enter" + tip + ":"); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (StringUtils.isNotBlank(ipt)) { returnipt; }}throw new MybatisPlusException("Please enter the correct one" + tip + "!"); } public static void main(String[] args) { // Code generator AutoGenerator mpg = new AutoGenerator(); // Global configuration GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("kenx"); gc.setOpen(false); // gc.setSwagger2(true); Entity attribute Swagger2 annotation mpg.setGlobalConfig(gc); // Data source configuration DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/blog? useUnicode=true&useSSL=false&characterEncoding=utf8"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root"); mpg.setDataSource(dsc); / / package configuration PackageConfig pc = new PackageConfig(); // pc.setModulename (scanner(" module name ")); pc.setParent("cn.soboys.blogapi"); mpg.setPackageInfo(pc); // Custom configuration InjectionConfig cfg = new InjectionConfig() { @Override public void initMap(a) { // to do nothing}};// If the template engine is freemarker String templatePath = "/templates/mapper.xml.ftl"; // If the template engine is Velocity // String templatePath = "/templates/mapper.xml.vm"; // Customize the output configuration List<FileOutConfig> focList = new ArrayList<>(); // Custom configurations are printed first focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // Customize the output file name. If your Entity has a prefix or suffix, note that the XML name will change accordingly!! return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper"+ StringPool.DOT_XML; }});/* cfg.setFileCreate(new IFileCreate() { @Override public boolean isCreate(ConfigBuilder configBuilder, FileType FileType, String filePath) {// Check whether the custom folder needs to create checkDir(" call the default directory created, custom directory used "); If (fileType == filetype.mapper) {if (fileType == filetype.mapper) {return false! new File(filePath).exists(); } // allow template files to be generated. }}); * / cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // Configure the template TemplateConfig templateConfig = new TemplateConfig(); // Configure a custom output template FTL /. Vm is automatically identified based on the template engine in use // templateConfig.setEntity("templates/entity2.java"); // templateConfig.setService(); // templateConfig.setController(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // Policy configuration StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); / / strategy. SetSuperEntityClass (" your parent entity, there is no need not set!" ); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); // Public parent class / / strategy. SetSuperControllerClass (" your parent controller, no need not set up!" ); // Public fields written in the parent class strategy.setSuperEntityColumns("id"); strategy.setInclude(scanner("Table name, separated by multiple Commas").split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(newFreemarkerTemplateEngine()); mpg.execute(); }}Copy the code

Generated CRUD

This is successful, saves a lot of development time and provides us with development efficiency

Then we just delete the unwanted code based on the business

Mybatis- plus3.4. x(springBoot2.4. x)