文章目录
- mybatis-plus代码生成
- 前言
- 一、mybatis-plus是什么?
- 二、使用步骤
- 1.引入依赖
- 2.代码
- 总结
前言
AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
一、mybatis-plus是什么?
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
二、使用步骤 1.引入依赖代码如下(示例):
2.代码com.baomidou mybatis-plus-boot-starter 3.0.5 org.freemarker freemarker 2.3.31
代码如下(示例):
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
// 策略配置
StrategyConfig strategy = new StrategyConfig();
// 作者
gc.setAuthor("lzy");
// 数据库密码
dsc.setPassword("xxxx");
// 数据库url
dsc.setUrl("jdbc:mysql://xxxxx:3306/xxxxx?useUnicode=true&useSSL=false&characterEncoding=utf8");
// 需要创建的表名,什么都不填生成所有
strategy.setInclude("admin");
// 全局配置
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setBaseResultMap(true);
gc.setOpen(false);
gc.setDateType(DateType.ONLY_DATE);
mpg.setGlobalConfig(gc);
// 数据源配置
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("");
pc.setParent("com.xx.xx");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 策略配置
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
List focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/src/main/java/com/xxx/xxx/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 自定义模板配置
TemplateConfig tc = new TemplateConfig();
tc.setServiceImpl("/templates/serviceImpl.java");
tc.setXml(null);
mpg.setTemplate(tc);
mpg.execute();
模板:
MyBatis-Plus代码生成器
总结
根据自己需求,更改配置即可。



