Author: Tangyuan

Personal blog: Javalover.cc

preface

Hello everyone, I am Tang Yuan, today to bring you is “SpringBoot in automatic code generation – based on Mybatis-Plus”, I hope to help you, thank you

The article is purely original, personal summary is inevitable mistakes, if so, please reply in the comment section or background private letter, thanks

Introduction to the

There are many ways of automatic code generation based on Mybatis-Plus. Here are two ways I am using:

  • Native code generation: Mybatis-Plus official
  • Online code generation: third party

These two kinds have their advantages and disadvantages, depending on which one you like

I heard that Idea also has auto-generated plugins, but I haven’t seen them yet, I think these two are enough (but I don’t know when I will use them).

Some officials, may ask, since Mybatis-Plus official website has an example, why also write here?

For those of us who are not familiar with template engines, we can omit some of the configuration introduced on the official website, thus reducing the time for debugging (because the default template generation configuration is sufficient, we do not need to touch the template syntax and so on).

Native code generation

Is in their own projects, write a Java program, configure a variety of parameters, can be automatically generated after the start

The advantage of this approach is that it generates directly into the local project without having to manually copy and paste

The downside is that there’s a lot of configuration to start with (but it’s all for good)

The good news is that the code below is annotated, and the other good news is that the generated code is also annotated (especially useful for entity class field annotations).

  1. Configuration of pom. The 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 auto-build is used -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.16</version>
    </dependency>
    Copy the code
  2. Automatic code generation Java main program: see the official website

    // Demo example, execute main method console input module table name press enter automatically generated corresponding project directory
    public class GenerateCode {
    
        /** * 

    * 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(); // 1. Global configuration GlobalConfig gc = new GlobalConfig(); // Project root directory String projectPath = System.getProperty("user.dir"); // Output directory of generated code: usually this is fixed, there is no need to write the specific package, because the package name will be configured separately below gc.setOutputDir(projectPath + "/src/main/java"); // Generate the author of the code gc.setAuthor("javalover"); // Does the generated directory automatically open after the code is generated: we don't need it here, because it is generated to the current project gc.setOpen(false); // Set the 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&serverTimezo ne=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: concatenate with the output directory above (ourDir+parent) pc.setParent("cn.stylefeng.guns.modular.business"); // check the moduleName input from the command line: concatenate it with the package name above (outDir+parent+moduleName). The generated code will be placed under this module pc.setModuleName(scanner("Module name")); mpg.setPackageInfo(pc); // 4. Configure policies StrategyConfig strategy = new StrategyConfig(); // Automatically generate entity class naming: database mapping to entity class, underline to hump strategy.setNaming(NamingStrategy.underline_to_camel); // If this is not set, it follows the naming of the entity class above strategy.setColumnNaming(NamingStrategy.underline_to_camel); // open TableField annotations, such as @tablefield ("car_name") strategy.setEntityTableFieldAnnotationEnable(true); // Add the package name to the parent class of the entity class strategy.setSuperEntityClass("cn.stylefeng.roses.kernel.db.api.pojo.entity.BaseEntity"); // The parent class of the mapping class: if there is one, configure it, remember to add the package name strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper"); // The parent class of the service interface: if it exists, add the package name strategy.setSuperServiceClass("com.baomidou.mybatisplus.extension.service.IService"); // The parent of the service implementation class: if it exists, add the package name strategy.setSuperServiceImplClass("com.baomidou.mybatisplus.extension.service.impl.ServiceImpl"); // Add the package name to the parent class of the controller class // strategy.setSuperControllerClass(""); // lombok: Whether to enable Lombok annotations such as @data, @equalSandhashCode (callSuper = true) strategy.setEntityLombokModel(true); // @restController annotation of a Controller: Whether to enable it. If not, @Controller is enabled by default strategy.setRestControllerStyle(true); // Monitor the command line input: table name strategy.setInclude(scanner("Table name, separated by multiple Commas").split(",")); // Controller request mapping URL style: hump to hyphen, such as "carList"-> "car-list" strategy.setControllerMappingHyphenStyle(true); // Set the table prefix: after setting this, the generated class name and Controller request mapping will not contain the table prefix // Set @requestMapping ("/ GPS /car") instead of @requestMapping ("/ GPS /gps-car") // The class name is the same strategy.setTablePrefix("gps"); mpg.setStrategy(strategy); 5. Configure the template engine // The velocity template is used by default // mpg.setTemplateEngine(new VelocityTemplateEngine());mpg.execute(); }}Copy the code

    Start the program, in the command line input package name, table name, wait for the completion of the operation can be

    The generated directory structure is as follows:

    As you can see, the basic framework is in place

    Let’s look at the generated Entity file:

    Car.java

    /** * <p> * Vehicle management * </p> **@author javalover
     * @sinceThe 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;
    
        /**
         * 车辆颜色
         */
        @TableField("car_color")
        private String carColor;
    
        /** * driver */
        @TableField("car_driver")
        private String carDriver;
    
        /**
         * 车辆价格
         */
        @TableField("car_price")
        private BigDecimal carPrice;
    
        /** ** fuel consumption */
        @TableField("fuel_consumption")
        private BigDecimal fuelConsumption;
    
        /** ** license plate */
        @TableField("car_number")
        private String carNumber;
    
        /** ** *
        @TableField("frame_number")
        private String frameNumber;
    
        /** ** load */
        @TableField("load_weight")
        private BigDecimal loadWeight;
    
        /** ** car photo */
        @TableField("car_img")
        private String carImg;
    
        /** * Vehicle real-time positioning */
        @TableField("car_location")
        private String carLocation;
    }
    
    Copy the code

    As you can see, the annotation is very detailed ah, how good (field annotation is according to the database annotation).

Online code generation

Is in the third party’s website, configure various parameters, click on the generation, and then download to the local

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

Weakness is

  • Need to configure a small database online, upload SQL statements

  • Once generated, it needs to be pulled into a local project

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

In fact, its disadvantages are caused by its simplicity

This is more suitable for new projects, want to quickly start the experience of friends

Because the online operation is very simple, here gives the link, the specific operation we will know under the experience

Online link: gen.stylefeng.cn/#/createCod…

conclusion

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

Angle 1: An example based on Mybatis-Plus official website (flexible and full of features)

Angle 2: Online generation based on third party (simple, quick to install)

Afterword.

And finally, thank you for watching. Thank you

Expect a thumbs-up from the officials