Note the official changes to Baomidou:

1. If you only use Mybatis – Plus, please refer to it

2. If a code generator is needed, it needs to be introduced separately. In version 3.0.6 of Mybatis – Plus, the generator is in the same project as Mybatis – Plus, and in later versions, the code generator is independently as Mybatis – Plus-generate project

The AutoGenerator class cannot be found using the latest mybatis- Plus when writing a new project because I haven’t paid attention to it for a long time.

<! -- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-generator -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.1 track</version>
</dependency>
<! Freemarker template engine dependencies -->
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
Copy the code

Below is the demo code, need to pay attention to the things are written in the comments, if you feel not detailed enough, I leave a message to add.

public class MybatisPlusGenerator {

    /** * Submodule name * project folder name, if there are multiple submodules, need to be modified for different modules * for example, parent has two modules: user, email, If springboot initualizr generates a single project, leave it blank */
    private static final String CMS_MODULE_NAME = "/email-delivery-platform"; 
    /** * Parent package name */
    private static final String CMS_PACKAGE_CONFIG_PARENT = "com.genius.mail";

    /** * After modifying the path and the table to be generated in reverse, run it directly. * /
    public static void main(String[] args) {
        // If tables is empty, all tables will be generated. It is better to set it to empty only during initialization. After that, fill in the table to be operated; otherwise, the existing content of other services will be overwritten
        String[] tables = {""};
        // Whether to generate only entity and XML, to generate Controller, Service, Mapper: false
        boolean isOnlyModel = false;

        // Attribution
        String author = "";

        // Perform code generation
        generator(CMS_MODULE_NAME, CMS_PACKAGE_CONFIG_PARENT, tables, isOnlyModel, author);
    }

    /** * MySQL generates ** in reverse@paramModuleName moduleName used to construct the generated root path location *@paramPackageConfigParent Specifies the parent package location * of the generated class@paramTableNames An array of tables to be generated *@paramIsOnlyModel Whether only Entity and XML * are generated@paramAuthor Indicates the author's name */
    private static void generator(String moduleName, String packageConfigParent, String[] tableNames, boolean
            isOnlyModel, String author) {
        AutoGenerator mpg = new AutoGenerator();
        // Project root path
        String projectPath = System.getProperty("user.dir") + moduleName;
        // Select freemarker engine without setting default Veloctiy
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        // If the template engine is freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // If the template engine is Velocity
// String templatePath = "/templates/mapper.xml.vm";

        // 1. Global configuration
        GlobalConfig gc = new GlobalConfig();
        // Output position
        gc.setOutputDir(projectPath + "/src/main/java");
        // Add the author
        gc.setAuthor(author);
        // Overwrite a file with the same name
        gc.setFileOverride(true);
        / / add a swagger
        gc.setSwagger2(false);
        // Change the ActiveRecord feature not required to false
        gc.setActiveRecord(true);
        // XML level 2 cache is disabled
        gc.setEnableCache(false);
        // XML ResultMap
        gc.setBaseResultMap(true);
        // XML columList
        gc.setBaseColumnList(true);
        // Whether to generate kotlin code
        gc.setKotlin(false);
        // Customize the file name, note that %s will automatically populate the table entity attributes!
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
        mpg.setGlobalConfig(gc);

        // 2. Data source configuration
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUrl("jdbc:mysql://localhost:3306/test? characterEncoding=utf8&serverTimezone=Asia/Shanghai");
        dsc.setUsername("root");
        dsc.setPassword("root");
        /* dsc.setTypeconvert (new MySqlTypeConvert(){DbColumnType processTypeConvert(String) public DbColumnType processTypeConvert(String Println (" convert type: "+ fieldType) {system.out.println (" convert type:" + fieldType); // Attention!! ProcessTypeConvert has a default conversion. If it is not the result you want, please customize it or return it directly. return super.processTypeConvert(fieldType); }}); * /
        mpg.setDataSource(dsc);

        // 3. Configure policies
        // Customize the fields to be filled
        List<TableFill> tableFillList = new ArrayList<>();
        tableFillList.add(new TableFill("create_time", FieldFill.INSERT));
        tableFillList.add(new TableFill("modify_time", FieldFill.INSERT_UPDATE));

        StrategyConfig strategy = new StrategyConfig();
        / / add default filler fields comments: @ TableField (fill = FieldFill. INSERT_UPDATE) | @ TableField (fill = FieldFill. INSERT)
        strategy.setLogicDeleteFieldName("dr");
        strategy.setTableFillList(tableFillList);
        // Underline the hump name
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        // Add Lombok to the entity
        strategy.setEntityLombokModel(true);
        // Use rest style Controller
        strategy.setRestControllerStyle(true);
        // Remove the table prefix
// strategy.setTablePrefix(new String[]{"sys_"});
        // Global uppercase name ORACLE note
        // strategy.setCapitalMode(true);
        // This can be changed to your table prefix
        // Table name generation strategy: change the underline to hump
        // Comment out all tables that need to be generated
        if (ArrayUtils.isNotEmpty(tableNames)) {
            strategy.setInclude(tableNames);
        }
        // Exclude the generated table
        //strategy.setExclude(new String[]{"sys_test"});
        // Define the entity parent class
        // strategy.setSuperEntityClass("com.yonyou.mphplus.BaseEntity");
        // Define the public field of the entity's parent class
        // strategy.setSuperEntityColumns(new String[] { "creator", "create_time" });
        // Customize the mapper parent class
        // strategy.setSuperMapperClass("com.yonyou.mphplus.BaseMapper");
        // Customize the service parent class
        // strategy.setSuperServiceClass("com.yonyou.mphplus.BaseService");
        // Custom service implementation class parent class
        // strategy.setSuperServiceImplClass("com.yonyou.mphplus.BaseServiceImpl");
        // Customize the controller parent class
        // strategy.setSuperControllerClass("com.yonyou.mphplus.BaseController");
        // whether to generate field constants (default false)
        // public static final String ID = "test_id";
        //strategy.setEntityColumnConstant(true);
        // Whether [entity] is a builder model (default false)
        // public User setName(String name) {this.name = name; return this; }
        //strategy.setEntityBuilderModel(true);
        // Customize the fields to be filled
// List
      
        tableFillList = new ArrayList<>();
      
// tableFillList.add(new TableFill("ASDD_SS", FieldFill.INSERT_UPDATE));
// strategy.setTableFillList(tableFillList);
        mpg.setStrategy(strategy);

        // 4. Package configuration
        PackageConfig pc = new PackageConfig();
        pc.setParent(packageConfigParent);
        pc.setController("controller");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setEntity("entity");
        pc.setMapper("mapper");
        mpg.setPackageInfo(pc);

       /* / insert custom configuration, ${cfg. ABC} InjectionConfig CFG = new InjectionConfig() {@override public void initMap() { Map
      
        map = new HashMap<>(16); map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp"); this.setMap(map); }}; List
       
         focList = new ArrayList<>(); focList.add(new FileOutConfig("/templates/list.html.vm") { @Override public String outputFile(TableInfo tableInfo) { // The custom input file name return "/ SRC/main/resources/static/" + tableInfo. GetEntityName () +" ListIndex. HTML "; }}); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); * /
       
      ,>

        // 5. Customize configuration
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap(a) {}};// Custom output configuration: output XML to /resources/mapper
        List<FileOutConfig> focList = new ArrayList<>();
        // Custom configurations are printed first
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo t) {
                // Customize the output file name
                return projectPath + "/src/main/resources/mapper/" + t.getEntityName() + "Mapper"+ StringPool.DOT_XML; }}); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg);// 6. Configure the template and do not output XML to SRC
        TemplateConfig tc = new TemplateConfig();
        / / custom template configuration, can copy the source code mybatis - plus/SRC/main/resources/templates below content changes,
        / / put your project of SRC/main/resources/templates directory, the default name can not configuration, can also custom template name
// tc.setController("/templates/controller.java.vm");
// tc.setService("/templates/service.java.vm");
// tc.setServiceImpl("/templates/serviceImpl.java.vm");
// tc.setEntity("/templates/entity.java.vm");
// tc.setMapper("/templates/mapper.java.vm");
// tc.setXml("/templates/mapper.xml.vm");
// // None of the above modules will be generated if set to null or null. Later Settings are required to prevent code overwriting
        // Do not output XML to SRC
        tc.setXml(null);
        // Whether to generate only entities and XML
        if (isOnlyModel) {
            tc.setController(null);
            tc.setService(null);
            tc.setServiceImpl(null);
            tc.setMapper(null);
        }
        mpg.setTemplate(tc);

        // Perform the build
        mpg.execute();

        // Print injection Settings
        // System.err.println(mpg.getCfg().getMap().get("abc"));}}Copy the code