Automatic code generation in SpringBoot - based on mybatis plus

Posted by Felex on Sat, 19 Feb 2022 08:11:18 +0100

Author: Tangyuan

Personal blog: javalover cc

preface

Shopping rebate https://m.cpa5.cn/

Hello, I'm tangyuan. Today I bring you automatic code generation in SpringBoot - based on mybatis plus. I hope it will be helpful to you. Thank you

The article is purely original, and personal summary will inevitably make mistakes. If so, please reply in the comment area or send a private message backstage. Thank you

brief introduction

There are many ways of automatic code generation based on mybatis plus. Here are two methods I am using:

  • Local code generation: mybatis plus official
  • Online code generation: Third Party

These two have their own advantages and disadvantages. It depends on which one you like

I heard that Idea also has auto generated plug-ins, but I haven't seen them yet. I think they are enough (but I'm not sure when I use the plug-ins, I'll find that there are good things in the dark)

Some officials may want to ask, since there are examples on the official website of mybatis plus, why should they write them here?

This is because for people like me who are not familiar with the template engine, we can save some of the configurations introduced on the official website, so as to reduce our debugging time (because the default template generation configuration is enough, and we don't need to touch those template syntax)

Local code generation

It is to write a Java program in your own project, configure various parameters, and automatically generate it after startup

The advantage of this method is that it can be generated directly to the local project without manual copying and pasting

The disadvantage is that there are many configurations at the beginning (but once and for all)

Well, let's start with the code. The good news is that the following codes have comments. Another good news is that the generated code also has comments (especially the field annotation of entity class, which is very practical)

  1. Configure POM xml

    <!-- mybatis-plus Code generator  -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-generator</artifactId>
        <version>3.4.0</version>
    </dependency>
    <!-- velocity Template engine for mybatis-plus Code generator  -->
    <dependency>
        <groupId>org.apache.velocity</groupId>
        <artifactId>velocity-engine-core</artifactId>
        <version>2.3</version>
    </dependency>
    <!-- lombok Automatic generation will use-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.16</version>
    </dependency>
    
  2. Java main program for automatically generating code: refer to the official website

    // Demo example: execute the main method, input the table name of the module on the console, and press enter to automatically generate the table name in the corresponding project directory
    public class GenerateCode {
    
        /**
         * <p>
         * Read console content
         * </p>
         */
        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)) {
                    return ipt;
                }
            }
            throw new MybatisPlusException("Please enter the correct" + tip + "!");
        }
    
        public static void main(String[] args) {
            // Code generator 
            AutoGenerator mpg = new AutoGenerator();
    
            // 1. Global configuration
            GlobalConfig gc = new GlobalConfig();
            // Project root directory
            String projectPath = System.getProperty("user.dir");
            // Output directory of generated code: generally, this is fixed. There is no need to write a specific package here, because the package name will be configured separately below
            gc.setOutputDir(projectPath + "/src/main/java");
            // The author who generated the code
            gc.setAuthor("javalover");
            // Whether to automatically open the generated directory after generating code: we don't need it here, because it is generated to the current project
            gc.setOpen(false);
            // Set global configuration
            mpg.setGlobalConfig(gc);
    
            // 2. Data source configuration
            DataSourceConfig dsc = new DataSourceConfig();
            dsc.setUrl("jdbc:mysql://localhost:3306/guns?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=CTT&nullCatalogMeansCurrent=true");
            dsc.setDriverName("com.mysql.cj.jdbc.Driver");
            dsc.setUsername("root");
            dsc.setPassword("root");
            mpg.setDataSource(dsc);
    
            // 3. Package configuration
            PackageConfig pc = new PackageConfig();
            // Set package name: splice with the output directory above (ourDir+parent)
            pc.setParent("cn.stylefeng.guns.modular.business");
            // Detect the module name entered on the command line: splice it with the above package name (outDir+parent+moduleName), and the generated code will be placed under this module
            pc.setModuleName(scanner("Module name"));
            mpg.setPackageInfo(pc);
    
            // 4. Policy configuration
            StrategyConfig strategy = new StrategyConfig();
            // Automatic generation of entity class naming: database mapping to entity class, underline to hump
            strategy.setNaming(NamingStrategy.underline_to_camel);
            // If it is not set here, it will follow the naming setting of the above entity class
            strategy.setColumnNaming(NamingStrategy.underline_to_camel);
            // Field annotation: Here we open the annotation of the table field, such as @ TableField("car_name")
            strategy.setEntityTableFieldAnnotationEnable(true);
            // Parent class of entity class: if any, configure it. Remember to add package name
            strategy.setSuperEntityClass("cn.stylefeng.roses.kernel.db.api.pojo.entity.BaseEntity");
            // Parent class of mapping class: configure if any, and remember to add package name
            strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper");
            // Parent class of service interface: configure if any, and remember to add package name
            strategy.setSuperServiceClass("com.baomidou.mybatisplus.extension.service.IService");
            // Parent class of service implementation class: configure if any, and remember to add package name
            strategy.setSuperServiceImplClass("com.baomidou.mybatisplus.extension.service.impl.ServiceImpl");
            // Parent class of controller class: configure if any, and remember to add package name
            // strategy.setSuperControllerClass("");
    
            // Lombok: whether to open the annotation of Lombok, such as @ Data,@EqualsAndHashCode(callSuper = true)
            strategy.setEntityLombokModel(true);
            // Comment on @ RestController of Controller: whether to enable it. If not, it defaults to @ Controller
            strategy.setRestControllerStyle(true);
            // Monitoring command line input: table name
            strategy.setInclude(scanner("Table name, separated by multiple English commas").split(","));
            // The request mapping url Style of the controller: hump to hyphen, such as "Carlist" - > "car list"
            strategy.setControllerMappingHyphenStyle(true);
            // After setting the prefix in the requested table and Controller, the generated table name will not contain the prefix
            // Set to @ RequestMapping("/gps/car") instead of @ requestmapping ("/ GPS / GPS car")
            // The same is true for class names
            strategy.setTablePrefix("gps");
            mpg.setStrategy(strategy);
    
            // 5. Configure template engine
            // The velocity template is adopted by default
    //        mpg.setTemplateEngine(new VelocityTemplateEngine());
            mpg.execute();
        }
    }
    
    

    Start the program, enter the package name and table name on the command line, and wait for the operation to be completed

    The generated directory structure is as follows:

    As you can see, the basic framework is available

    Let's take a look at the generated entity file:

    Car.java

    /**
     * <p>
     * Vehicle management
     * </p>
     *
     * @author javalover
     * @since 2021-04-22
     */
    @Data
    @EqualsAndHashCode(callSuper = true)
    @TableName("gps_car")
    public class Car extends BaseEntity {
    
        private static final long serialVersionUID = 1L;
    
        /**
         * Vehicle id
         */
        @TableId("car_id")
        private Long carId;
    
        /**
         * Company id
         */
        @TableField("company_id")
        private Long companyId;
    
        /**
         * Vehicle name
         */
        @TableField("car_name")
        private String carName;
    
        /**
         * Vehicle type
         */
        @TableField("car_type")
        private Integer carType;
    
        /**
         * Vehicle color
         */
        @TableField("car_color")
        private String carColor;
    
        /**
         * driver
         */
        @TableField("car_driver")
        private String carDriver;
    
        /**
         * Vehicle price
         */
        @TableField("car_price")
        private BigDecimal carPrice;
    
        /**
         * oil consumption
         */
        @TableField("fuel_consumption")
        private BigDecimal fuelConsumption;
    
        /**
         * license plate number
         */
        @TableField("car_number")
        private String carNumber;
    
        /**
         * Frame number
         */
        @TableField("frame_number")
        private String frameNumber;
    
        /**
         * load
         */
        @TableField("load_weight")
        private BigDecimal loadWeight;
    
        /**
         * Car photos
         */
        @TableField("car_img")
        private String carImg;
    
        /**
         * Vehicle real-time positioning
         */
        @TableField("car_location")
        private String carLocation;
    }
    
    

    You can see that the annotation is very detailed. How good it is (the annotation of the field is based on the annotation of the database)

Online code generation

That is, configure various parameters on the third-party website, click generate, and then download to the local

The advantage of this method is that there is not much configuration in the early stage and it is easy to use

The disadvantage is

  • You need to configure a small database online and upload SQL statements

  • After generation, it needs to be pulled to the local project

  • Not flexible enough, such as the configuration of parent classes

In fact, its shortcomings are caused by its simplicity

This is more suitable for new projects and friends who want to get started quickly

Because the online operation is very simple, here is a link. You will know the specific operation through your experience

Online links: https://gen.stylefeng.cn/#/createCode

summary

There are many ways to automatically generate code, and here is just the tip of the iceberg

Corner 1: example based on mybatis plus official website (flexible and fully functional)

Corner 2: Online generation based on third party (simple and quick to use)

Postscript

Finally, thank you for watching, thank you

Look forward to the praise of officials