Mybatis generator automatically generates code and integrates swaggerui

  1. Introduce dependency:
<!-- MyBatis generator -->
<dependency>
   <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.3.7</version>
</dependency>
<!--Mysql Database driven-->
  <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.15</version>
  </dependency>
  <!--Swagger-UI API Document production tools-->
  <dependency>
       <groupId>io.springfox</groupId>
       <artifactId>springfox-swagger2</artifactId>
       <version>2.7.0</version>
   </dependency>
   <dependency>
       <groupId>io.springfox</groupId>
       <artifactId>springfox-swagger-ui</artifactId>
       <version>2.7.0</version>
   </dependency>

2. Add a configuration file in the resource directory:

generatorConfig.xml, please modify the generated model, mapper and XML path according to the actual situation

<?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>
    <properties resource="generator.properties"/>
    <context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <property name="javaFileEncoding" value="UTF-8"/>
        <!-- Generate serialization method for model-->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
        <!-- For generation Java Create a model toString Method -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
        <!--generate mapper.xml Overwrite the original file when-->
        <plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" />
        <!--Can customize build model Code comment for-->
        <commentGenerator type="com.mybatis.generator.util.CommentGenerator">
            <!-- Remove automatically generated comments or not true: Yes, false:no -->
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>
        <!--Configure database connection-->
        <jdbcConnection driverClass="${jdbc.driverClass}"
                        connectionURL="${jdbc.connectionURL}"
                        userId="${jdbc.userId}"
                        password="${jdbc.password}">
            <!--Solve mysql Driver upgrade to8.0Do not generate the specified database code after-->
            <property name="nullCatalogMeansCurrent" value="true" />
        </jdbcConnection>
        <!--Specified generation model Path-->
        <javaModelGenerator targetPackage="com.mybatis.generator.model" targetProject="src\main\java"/>
        <!--Specified generation mapper.xml Path-->
        <sqlMapGenerator targetPackage="com.mybatis.generator.mapper" targetProject="src\main\resources"/>
        <!--Specified generation mapper The path of the interface-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.mybatis.generator.mapper"
                             targetProject="src\main\java"/>
        <!--Generate all tables tableName Set as%-->
        <table tableName="%">
            <generatedKey column="id" sqlStatement="MySql" identity="true"/>
        </table>
    </context>
</generatorConfiguration>

generator.properties

jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://localhost:3306/mooc_one?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
jdbc.userId=root
jdbc.password=123456

3. Add CommentGenerator.java comment generator and generate code call class in util Directory:

CommentGenerator.java

package com.mybatis.generator.util;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;

import java.util.Properties;

/**
 * Custom comment builder
 */
public class CommentGenerator extends DefaultCommentGenerator {
    private boolean addRemarkComments = false;
    private static final String EXAMPLE_SUFFIX="Example";
    private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME="io.swagger.annotations.ApiModelProperty";

    /**
     * Set user configured parameters
     */
    @Override
    public void addConfigurationProperties(Properties properties) {
        super.addConfigurationProperties(properties);
        this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
    }

    /**
     * Add comments to fields
     */
    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable,
                                IntrospectedColumn introspectedColumn) {
        String remarks = introspectedColumn.getRemarks();
        //Judge whether to add remark information according to parameters and remark information
        if(addRemarkComments&& StringUtility.stringHasValue(remarks)){
//            addFieldJavaDoc(field, remarks);
            //Special characters in database need to be escaped
            if(remarks.contains("\"")){
                remarks = remarks.replace("\"","'");
            }
            //Add a swagger annotation to the model's fields
            field.addJavaDocLine("@ApiModelProperty(value = \""+remarks+"\")");
        }
    }

    /**
     * Add comments to the model's fields
     */
    private void addFieldJavaDoc(Field field, String remarks) {
        //Document comment start
        field.addJavaDocLine("/**");
        //Get comment information for database fields
        String[] remarkLines = remarks.split(System.getProperty("line.separator"));
        for(String remarkLine:remarkLines){
            field.addJavaDocLine(" * "+remarkLine);
        }
        addJavadocTag(field, false);
        field.addJavaDocLine(" */");
    }

    @Override
    public void addJavaFileComment(CompilationUnit compilationUnit) {
        super.addJavaFileComment(compilationUnit);
        //Only add import of swagger annotation class in model
        if(!compilationUnit.isJavaInterface()&&!compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)){
            compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));
        }
    }
}

Generator.java

package com.mybatis.generator.util;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Code for MBG production
 */
public class Generator {
    public static void main(String[] args) throws Exception {
        //Warnings during MBG execution
        List<String> warnings = new ArrayList<String>();
        //When the generated code is duplicate, overwrite the original code
        boolean overwrite = true;
        //Read our MBG configuration file
        InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(is);
        is.close();

        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        //Create MBG
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        //Execute build code
        myBatisGenerator.generate(null);
        //Output warning information
        for (String warning : warnings) {
            System.out.println(warning);
        }
    }
}

Run the Generator.java main method to generate code automatically:

4. Add Swagger2 configuration class:
Swagger2Config.java:

package com.mybatis.generator.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @ClassName Swagger2Config
 * @Author lzl
 * @Description Swagger2 Configuration class
 * @Date 2020/3/14 11:45
 * @Version 1.0
 **/
@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //Generate API document for controller under current package
                .apis(RequestHandlerSelectors.basePackage("com.mybatis.generator.controller"))
                //Generate API document for Controller annotated with @ API
//                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                //Generate API documents for methods annotated with @ ApiOperation
//                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Interface document")
                .description("item")
                .contact("lzl")
                .version("1.0")
                .build();
    }
}

5. Add @ Api, @ ApiOperation annotation to the controller class:
ItemController.controller:

package com.mybatis.generator.controller;

import com.mybatis.generator.common.CommonResponse;
import com.mybatis.generator.common.ErrorCodeEnum;
import com.mybatis.generator.consts.CommonConsts;
import com.mybatis.generator.consts.PathConsts;
import com.mybatis.generator.model.ItemInfo;
import com.mybatis.generator.service.ItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @ClassName ItemController
 * @Author lzl
 * @Description Commodity interface
 * @Date 2020/3/14 10:40
 * @Version 1.0
 **/
@Api(tags = "ItemController",description = "Commodity management interface")
@RestController
@RequestMapping(value = PathConsts.ITEM_ROOT_PATH)
public class ItemController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ItemController.class);

    @Autowired
    private ItemService itemService;

    /**
     * @Author lzl
     * @Description Get all products
     * @Date 11:00 2020/3/14
     * @Param []
     * @return com.mybatis.generator.common.CommonResponse
     **/
    @ApiOperation("Get all products")
    @GetMapping(PathConsts.GET_ALL)
    public CommonResponse ItemInfos()
    {
        LOGGER.info("start to search itemInfos");
        List<ItemInfo> itemInfos = itemService.findAllItem();
        if (null == itemInfos || itemInfos.size() == CommonConsts.ZERO_RESULT)
        {
            LOGGER.info("item size is zero");
            return CommonResponse.response(ErrorCodeEnum.NOT_EXISTS);
        }
        LOGGER.info("search itemInfos success,size:{}",itemInfos.size());
        return CommonResponse.success(itemInfos);
    }
}

6. Operation project, the effect is as follows:
http://localhost:8080/swagger-ui.html#

Online test:

Published 6 original articles, praised 0 and visited 505
Private letter follow

Keywords: Mybatis Java JDBC MySQL

Added by JamesyBHOY on Sat, 14 Mar 2020 16:25:58 +0200