mybatis-plus automatically generates code to the corresponding model

Mainly thinking: 1. Assemble your own model name to generate code with a number
                 2. Dynamically obtain the path according to the model name
                 3. When generating code, judge according to the model, only generate the code of the current model object

1.maven 依赖
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>2.1-gamma</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
        </dependency>

Note: After adding this dependency, you need to remove the original mybatis and mybatis-spring dependencies to avoid conflicts, because mybatis-plus contains these two

2. Let me show you my project structure first



2. Automatically generate code tool classes

2.1 Use a number to assemble your own model name to generate code

String[] models = {"ssm-mapper","ssm-model","ssm-service","ssm-web"};

2.2. Dynamically obtain the path according to the model name

2.3 According to the model judgment when generating code, only the code of the current model object is generated

3. Tool class complete code

package com.spf.common.generator;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther ShuPF
 * @Create 2017/7/5 0005
 */

public class MybatisPlusUtils {

    public static void main(String[] args) {
        String[] models = {"ssm-mapper","ssm-model","ssm-service","ssm-web"};
        for (String model : models) {
            shell(model);
        }
    }

    private static void shell(String model){
        File file = new File(model);
        String path = file.getAbsolutePath();
        //path = path.substring(0, path.lastIndexOf(File.separator));
        AutoGenerator mpg = new AutoGenerator();
        // global configuration
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(path+"/src/main/java");
        gc.setFileOverride(true);
        gc.setActiveRecord(true);
        gc.setEnableCache(false);// XML secondary cache
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList
        gc.setAuthor("SPF");

        // Customize file naming, note that %s will automatically populate table entity properties!
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("I%sService");
        gc.setServiceImplName("I%sServiceImpl");
        gc.setControllerName("%sController");
        mpg.setGlobalConfig(gc);

        // data source configuration
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert(){
            // Custom database table field type conversion [optional]
            @Override
            public DbColumnType processTypeConvert(String fieldType) {
                System.out.println("Conversion type: " + fieldType);
                // Notice! ! There is a default type conversion in processTypeConvert. If it is not the effect you want, please customize the return, or return directly as follows.
                return super.processTypeConvert(fieldType);
            }
        });
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("SPF940805.");
        dsc.setUrl("jdbc:mysql:///test?characterEncoding=utf8");
        mpg.setDataSource(dsc);

        // policy configuration
        StrategyConfig strategy = new StrategyConfig();
        // strategy.setCapitalMode(true);// Global uppercase name ORACLE Note
        strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });// This can be modified to your table prefix
        strategy.setNaming(NamingStrategy.underline_to_camel);// table name generation strategy
        strategy.setInclude(new String[] { "user_info" }); // table to be generated
        // strategy.setExclude(new String[]{"test"}); // exclude generated table
        // custom entity parent class
        //strategy.setSuperEntityClass("com.spf.model.Entity");
        // custom entity, public fields
        //strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
        // custom mapper parent class
        // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
        // custom service parent class
        //strategy.setSuperServiceClass("com.baomidou.demo.TestService");
        // custom service implementation class parent class
        //strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
        // custom controller parent class
        //strategy.setSuperControllerClass("com.baomidou.demo.TestController");
        // [Entity] Whether to generate field constants (default false)
        // public static final String ID = "test_id";
        // strategy.setEntityColumnConstant(true);
        // [Entity] Whether it is a builder model (default false)
        // public User setName(String name) {this.name = name; return this;}
        // strategy.setEntityBuliderModel(true);
        mpg.setStrategy(strategy);

        // package configuration
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.spf");
        pc.setController("controller");
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setServiceImpl("impl");
        //pc.setModuleName("test");
        mpg.setPackageInfo(pc);

        // Inject custom configuration, you can use cfg.abc in VM [optional]
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                this.setMap(map);
            }
        };

        // custom xxList.jsp generation
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
//    focList.add(new FileOutConfig("/template/list.jsp.vm") {
//       @Override
//       public String outputFile(TableInfo tableInfo) {
// // Custom input file name
//          return "D://my_" + tableInfo.getEntityName() + ".jsp";
//       }
//    });
// cfg.setFileOutConfigList(focList);
//    mpg.setCfg(cfg);

        // Adjust xml to generate directory demo
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return "/develop/code/xml/" + tableInfo.getEntityName() + ".xml";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // Turn off the default xml generation and adjust the generation to the root directory
        TemplateConfig tc = new TemplateConfig();
        if ("ssm-mapper".equals(model)) {
            tc.setController(null);
            tc.setEntity(null);
            tc.setService(null);
            tc.setServiceImpl(null);
        } else if ("ssm-model".equals(model)) {
            tc.setController(null);
            tc.setService(null);
            tc.setServiceImpl(null);
            tc.setMapper(null);
            tc.setXml(null);
        }  else if ("ssm-service".equals(model)) {
            tc.setController(null);
            tc.setMapper(null);
            tc.setXml(null);
            tc.setEntity(null);
        } else if ("ssm-web".equals(model)) {
            tc.setMapper(null);
            tc.setXml(null);
            tc.setService(null);
            tc.setServiceImpl(null);
            tc.setEntity(null);
        }
        mpg.setTemplate(tc);

        // To customize the template configuration, you can copy the source code mybatis-plus/src/main/resources/template and modify the following content,
        // Put your own project's src/main/resources/template directory, the default name can not be configured, or you can customize the template name
        // TemplateConfig tc = new TemplateConfig();
        // tc.setController("...");
        // tc.setEntity("...");
        // tc.setMapper("...");
        // tc.setXml("...");
        // tc.setService("...");
        // tc.setServiceImpl("...");
        // If any of the above modules is set to empty OR Null, the module will not be generated.
        // mpg.setTemplate(tc);

        // execute the build
        mpg.execute();

        // print injection settings [optional]
        System.err.println(mpg.getCfg().getMap().get("abc"));
    }

}

OK!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325984446&siteId=291194637