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


Shopping rebate

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  -->
    <!-- velocity Template engine for mybatis-plus Code generator  -->
    <!-- lombok Automatic generation will use-->
  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(;
            StringBuilder help = new StringBuilder();
            help.append("Please enter" + tip + ": ");
            if (scanner.hasNext()) {
                String ipt =;
                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
            // Whether to automatically open the generated directory after generating code: we don't need it here, because it is generated to the current project
            // Set global configuration
            // 2. Data source configuration
            DataSourceConfig dsc = new DataSourceConfig();
            // 3. Package configuration
            PackageConfig pc = new PackageConfig();
            // Set package name: splice with the output directory above (ourDir+parent)
            // 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"));
            // 4. Policy configuration
            StrategyConfig strategy = new StrategyConfig();
            // Automatic generation of entity class naming: database mapping to entity class, underline to hump
            // If it is not set here, it will follow the naming setting of the above entity class
            // Field annotation: Here we open the annotation of the table field, such as @ TableField("car_name")
            // Parent class of entity class: if any, configure it. Remember to add package name
            // Parent class of mapping class: configure if any, and remember to add package name
            // Parent class of service interface: configure if any, and remember to add package name
            // Parent class of service implementation class: configure if any, and remember to add package name
            // 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)
            // Comment on @ RestController of Controller: whether to enable it. If not, it defaults to @ Controller
            // 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"
            // 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
            // 5. Configure template engine
            // The velocity template is adopted by default
    //        mpg.setTemplateEngine(new VelocityTemplateEngine());

    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:

     * <p>
     * Vehicle management
     * </p>
     * @author javalover
     * @since 2021-04-22
    @EqualsAndHashCode(callSuper = true)
    public class Car extends BaseEntity {
        private static final long serialVersionUID = 1L;
         * Vehicle id
        private Long carId;
         * Company id
        private Long companyId;
         * Vehicle name
        private String carName;
         * Vehicle type
        private Integer carType;
         * Vehicle color
        private String carColor;
         * driver
        private String carDriver;
         * Vehicle price
        private BigDecimal carPrice;
         * oil consumption
        private BigDecimal fuelConsumption;
         * license plate number
        private String carNumber;
         * Frame number
        private String frameNumber;
         * load
        private BigDecimal loadWeight;
         * Car photos
        private String carImg;
         * Vehicle real-time positioning
        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:


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)


Finally, thank you for watching, thank you

Look forward to the praise of officials