• 代码生成器
    • 使用教程
      • 添加依赖
      • 编写配置
    • 自定义模板引擎
    • 自定义代码模板
    • 自定义属性注入
    • 字段其他信息查询注入

    代码生成器

    AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。

    特别说明:

    自定义模板有哪些可用参数?Github代码生成器 - 图1Gitee代码生成器 - 图2 AbstractTemplateEngine 类中方法 getObjectMap 返回 objectMap 的所有值都可用。

    演示效果图:

    relationship

    1. // 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
    2. public class CodeGenerator {
    3. /**
    4. * <p>
    5. * 读取控制台内容
    6. * </p>
    7. */
    8. public static String scanner(String tip) {
    9. Scanner scanner = new Scanner(System.in);
    10. StringBuilder help = new StringBuilder();
    11. help.append("请输入" + tip + ":");
    12. System.out.println(help.toString());
    13. if (scanner.hasNext()) {
    14. String ipt = scanner.next();
    15. if (StringUtils.isNotEmpty(ipt)) {
    16. return ipt;
    17. }
    18. }
    19. throw new MybatisPlusException("请输入正确的" + tip + "!");
    20. }
    21. public static void main(String[] args) {
    22. // 代码生成器
    23. AutoGenerator mpg = new AutoGenerator();
    24. // 全局配置
    25. GlobalConfig gc = new GlobalConfig();
    26. String projectPath = System.getProperty("user.dir");
    27. gc.setOutputDir(projectPath + "/src/main/java");
    28. gc.setAuthor("jobob");
    29. gc.setOpen(false);
    30. // gc.setSwagger2(true); 实体属性 Swagger2 注解
    31. mpg.setGlobalConfig(gc);
    32. // 数据源配置
    33. DataSourceConfig dsc = new DataSourceConfig();
    34. dsc.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8");
    35. // dsc.setSchemaName("public");
    36. dsc.setDriverName("com.mysql.jdbc.Driver");
    37. dsc.setUsername("root");
    38. dsc.setPassword("密码");
    39. mpg.setDataSource(dsc);
    40. // 包配置
    41. PackageConfig pc = new PackageConfig();
    42. pc.setModuleName(scanner("模块名"));
    43. pc.setParent("com.baomidou.ant");
    44. mpg.setPackageInfo(pc);
    45. // 自定义配置
    46. InjectionConfig cfg = new InjectionConfig() {
    47. @Override
    48. public void initMap() {
    49. // to do nothing
    50. }
    51. };
    52. // 如果模板引擎是 freemarker
    53. String templatePath = "/templates/mapper.xml.ftl";
    54. // 如果模板引擎是 velocity
    55. // String templatePath = "/templates/mapper.xml.vm";
    56. // 自定义输出配置
    57. List<FileOutConfig> focList = new ArrayList<>();
    58. // 自定义配置会被优先输出
    59. focList.add(new FileOutConfig(templatePath) {
    60. @Override
    61. public String outputFile(TableInfo tableInfo) {
    62. // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
    63. return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
    64. + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
    65. }
    66. });
    67. /*
    68. cfg.setFileCreate(new IFileCreate() {
    69. @Override
    70. public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
    71. // 判断自定义文件夹是否需要创建
    72. checkDir("调用默认方法创建的目录");
    73. return false;
    74. }
    75. });
    76. */
    77. cfg.setFileOutConfigList(focList);
    78. mpg.setCfg(cfg);
    79. // 配置模板
    80. TemplateConfig templateConfig = new TemplateConfig();
    81. // 配置自定义输出模板
    82. //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
    83. // templateConfig.setEntity("templates/entity2.java");
    84. // templateConfig.setService();
    85. // templateConfig.setController();
    86. templateConfig.setXml(null);
    87. mpg.setTemplate(templateConfig);
    88. // 策略配置
    89. StrategyConfig strategy = new StrategyConfig();
    90. strategy.setNaming(NamingStrategy.underline_to_camel);
    91. strategy.setColumnNaming(NamingStrategy.underline_to_camel);
    92. strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");
    93. strategy.setEntityLombokModel(true);
    94. strategy.setRestControllerStyle(true);
    95. // 公共父类
    96. strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
    97. // 写于父类中的公共字段
    98. strategy.setSuperEntityColumns("id");
    99. strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
    100. strategy.setControllerMappingHyphenStyle(true);
    101. strategy.setTablePrefix(pc.getModuleName() + "_");
    102. mpg.setStrategy(strategy);
    103. mpg.setTemplateEngine(new FreemarkerTemplateEngine());
    104. mpg.execute();
    105. }
    106. }

    更多详细配置,请参考代码生成器配置一文。

    使用教程

    添加依赖

    MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖:

    • 添加 代码生成器 依赖
    1. <dependency>
    2. <groupId>com.baomidou</groupId>
    3. <artifactId>mybatis-plus-generator</artifactId>
    4. <version>latest-version</version>
    5. </dependency>
    • 添加 模板引擎 依赖,MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引擎,如果都不满足您的要求,可以采用自定义模板引擎。

    Velocity(默认):

    1. <dependency>
    2. <groupId>org.apache.velocity</groupId>
    3. <artifactId>velocity-engine-core</artifactId>
    4. <version>latest-velocity-version</version>
    5. </dependency>

    Freemarker:

    1. <dependency>
    2. <groupId>org.freemarker</groupId>
    3. <artifactId>freemarker</artifactId>
    4. <version>latest-freemarker-version</version>
    5. </dependency>

    Beetl:

    1. <dependency>
    2. <groupId>com.ibeetl</groupId>
    3. <artifactId>beetl</artifactId>
    4. <version>latest-beetl-version</version>
    5. </dependency>

    注意!如果您选择了非默认引擎,需要在 AutoGenerator 中 设置模板引擎。

    1. AutoGenerator generator = new AutoGenerator();
    2. // set freemarker engine
    3. generator.setTemplateEngine(new FreemarkerTemplateEngine());
    4. // set beetl engine
    5. generator.setTemplateEngine(new BeetlTemplateEngine());
    6. // set custom engine (reference class is your custom engine class)
    7. generator.setTemplateEngine(new CustomTemplateEngine());
    8. // other config
    9. ...

    编写配置

    MyBatis-Plus 的代码生成器提供了大量的自定义参数供用户选择,能够满足绝大部分人的使用需求。

    • 配置 GlobalConfig
    1. GlobalConfig globalConfig = new GlobalConfig();
    2. globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
    3. globalConfig.setAuthor("jobob");
    4. globalConfig.setOpen(false);
    • 配置 DataSourceConfig
    1. DataSourceConfig dataSourceConfig = new DataSourceConfig();
    2. dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8");
    3. dataSourceConfig.setDriverName("com.mysql.jdbc.Driver");
    4. dataSourceConfig.setUsername("root");
    5. dataSourceConfig.setPassword("password");

    自定义模板引擎

    请继承类 com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine

    自定义代码模板

    1. //指定自定义模板路径, 位置:/resources/templates/entity2.java.ftl(或者是.vm)
    2. //注意不要带上.ftl(或者是.vm), 会根据使用的模板引擎自动识别
    3. TemplateConfig templateConfig = new TemplateConfig()
    4. .setEntity("templates/entity2.java");
    5. AutoGenerator mpg = new AutoGenerator();
    6. //配置自定义模板
    7. mpg.setTemplate(templateConfig);

    自定义属性注入

    1. InjectionConfig injectionConfig = new InjectionConfig() {
    2. //自定义属性注入:abc
    3. //在.ftl(或者是.vm)模板中,通过${cfg.abc}获取属性
    4. @Override
    5. public void initMap() {
    6. Map<String, Object> map = new HashMap<>();
    7. map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
    8. this.setMap(map);
    9. }
    10. };
    11. AutoGenerator mpg = new AutoGenerator();
    12. //配置自定义属性注入
    13. mpg.setCfg(injectionConfig);
    1. entity2.java.ftl
    2. 自定义属性注入abc=${cfg.abc}
    3. entity2.java.vm
    4. 自定义属性注入abc=$!{cfg.abc}

    字段其他信息查询注入

    relationship

    1. new DataSourceConfig().setDbQuery(new MySqlQuery() {
    2. /**
    3. * 重写父类预留查询自定义字段<br>
    4. * 这里查询的 SQL 对应父类 tableFieldsSql 的查询字段,默认不能满足你的需求请重写它<br>
    5. * 模板中调用: table.fields 获取所有字段信息,
    6. * 然后循环字段获取 field.customMap 从 MAP 中获取注入字段如下 NULL 或者 PRIVILEGES
    7. */
    8. @Override
    9. public String[] fieldCustom() {
    10. return new String[]{"NULL", "PRIVILEGES"};
    11. }
    12. })