mybatis-generator

MyBatis Generator官方文档
MyBatis Generator官方文档(Plugin)
插件可用于修改或添加由MyBatis Generator生成的对象。插件必须实现org.mybatis.generator.api.Plugin接口 。插件接口包含许多在代码生成过程的不同阶段调用的方法。任何特定插件通常都不需要实现整个界面。因此,大多数插件应该扩展适配器类org.mybatis.generator.api.PluginAdapter。适配器类提供基本的插件支持,并为大多数接口方法实现无操作方法(类似于Swing适配器类)。


实现插件的最佳方法是扩展 org.mybatis.generator.api.PluginAdapter类,并仅覆盖插件中所需的特定方法。
public class BasePlugin extends PluginAdapter { }

如果我们要在实体类上增加自定义注释和注解 只需要重写modelBaseRecordClassGenerated方法
package com.dolphin.mybatis.generator; import org.mybatis.generator.api.PluginAdapter; import org.mybatis.generator.api.dom.java.*; import org.mybatis.generator.api.IntrospectedTable; public class BasePlugin extends PluginAdapter { public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { // 增加注释 topLevelClass.addJavaDocLine("/**"); topLevelClass.addJavaDocLine("* 开发公司:青岛海豚数据技术有限公司"); topLevelClass.addJavaDocLine("* 版权:青岛海豚数据技术有限公司"); topLevelClass.addJavaDocLine("* Class"); topLevelClass.addJavaDocLine("* " + topLevelClass.getType().getShortName()); topLevelClass.addJavaDocLine("*"); topLevelClass.addJavaDocLine("* @author 系统"); topLevelClass.addJavaDocLine("* @created Create Time: " + new Date()); topLevelClass.addJavaDocLine("*/"); // 导入注解对应的开发包 Set set = new HashSet(); set.add(new FullyQualifiedJavaType("io.swagger.annotations.ApiModel")); set.add(new FullyQualifiedJavaType("lombok.Data")); topLevelClass.addImportedTypes(set); //导入注解对应的开发包 // 增加注解 topLevelClass.addAnnotation("@ApiModel" + "(value=https://www.it610.com/"" + topLevelClass.getType() + "\",description=\"" + introspectedTable.getRemarks() + "\")"); topLevelClass.addAnnotation("@Data"); } }

对应的修改
clientGenerated //生成mapper接口调用的方法 modelFieldGenerated //生成实体类每个字段调用的方法 modelSetterMethodGenerated //生成实体类字段set方法调用的方法 modelGetterMethodGenerated //生成实体类字段get方法调用的方法 clientxxxxxxxMethodGenerated //生成对应mapper接口内方法调用的方法 sqlMapXXXElementGenerated(XmlElement,IntrospectedTable)在生成SQL映射的每个元素时调用这些方法 sqlMapDocumentGenerated(Document,IntrospectedTable) sqlMapDocument(GeneratedXmlFile,IntrospectedTable)

对于额外Controller等额外文件,我们可以借助FreeMarker模板在指定位置创建文件,如Controller.ftl
package ${package_controller}; import io.swagger.annotations.Api; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import ${package_service}.${file_name}Service; import com.dolphin.common.tool.BaseController; /** * 开发公司:青岛海豚数据技术有限公司 * 版权:青岛海豚数据技术有限公司 * *${file_name}Controller * * @author 系统 * @created Create Time: ${date?string('yyyy-MM-dd hh:mm:ss')} */ @RestController @RequestMapping("/${module_name}") @CrossOrigin @Api(description = "相关的api") public class ${file_name}Controller extends BaseController {@Autowired public ${file_name}Service ${file_name?uncap_first}Service; }

将Controller.ftl里表达式的值替换掉就是一个初始的Controller.java文件了
新建FreeMarker模板工具类
package com.dolphin.mybatis.generator; import freemarker.cache.ClassTemplateLoader; import freemarker.cache.NullCacheStorage; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateExceptionHandler; import java.io.IOException; /** * 开发公司:青岛海豚数据技术有限公司 * 版权:青岛海豚数据技术有限公司 * * FreeMarkerTemplateUtils * * @author 刘志强 * @created Create Time: 2019/1/22 */ public class FreeMarkerTemplateUtils { private FreeMarkerTemplateUtils(){} private static final Configuration CONFIGURATION = new Configuration(Configuration.VERSION_2_3_22); static{ CONFIGURATION.setTemplateLoader(new ClassTemplateLoader(FreeMarkerTemplateUtils.class, "/generator/template")); CONFIGURATION.setDefaultEncoding("UTF-8"); CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); CONFIGURATION.setCacheStorage(NullCacheStorage.INSTANCE); }public static Template getTemplate(String templateName) throws IOException { try { return CONFIGURATION.getTemplate(templateName); } catch (IOException e) { throw e; } }public static void clearCache() { CONFIGURATION.clearTemplateCache(); } }

修改plugin标签,追加property标签填写文件路径。如下

修改modelBaseRecordClassGenerated方法
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { // 取出controller的value值 String packageController = properties.getProperty("controller"); if (packageController != null) { String packageService = properties.getProperty("service"); String[] mulu = properties.getProperty("controller").split("\\."); String moduleName = mulu[mulu.length - 1]; String fileName = topLevelClass.getType().getShortName(); String path = introspectedTable.getContext().getJavaModelGeneratorConfiguration().getTargetProject() + "/" + properties.getProperty("controller").replaceAll("\\.", "/"); File catalog = new File(path); catalog.mkdirs(); File mapperFile = new File(path + '/' + fileName + "Controller.java"); Template template = FreeMarkerTemplateUtils.getTemplate("Controller.ftl"); FileOutputStream fos = new FileOutputStream(mapperFile); Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"), 10240); Map dataMap = new HashMap(); dataMap.put("package_controller", packageController); dataMap.put("package_service", packageService); dataMap.put("module_name", moduleName); dataMap.put("file_name", fileName); dataMap.put("date", new Date()); template.process(dataMap, out); } }

MBG启动方式Java启动或者maven启动
Java启动
public class GenerateStartUp {public static void main(String[] args) { List warnings = new ArrayList(); try { boolean overwrite = true; ClassLoader classloader = Thread.currentThread().getContextClassLoader(); InputStream is = classloader.getResourceAsStream("mybatis-generator.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(is); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); } catch (SQLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvalidConfigurationException e) { e.printStackTrace(); } catch (XMLParserException e) { e.printStackTrace(); } for (String warning : warnings) { System.out.println(warning); } } }

maven启动 pom 文件增加plugin
org.mybatis.generator mybatis-generator-maven-plugin 1.3.5 mysql mysql-connector-java 5.1.21 org.mybatis.generator mybatis-generator-core 1.3.5 com.liuzhiqiang.tools generator-extend 2.1-SNAPSHOT truetrue src/main/resources/mybatis-generator.xml

【mybatis-generator】github地址

    推荐阅读