注意baomidou的官方改动:
1.如果只使用mybatis-plus可以参考
2.如果需要使用代码生成器则需要单独引入,在mybatis-plus3.0.6版本时生成器与mybatis-plus在同一项目中,之后的版本将代码生成器独立为mybatis-plus-generate项目
因为很久没关注,在写新项目时使用最新的mybatis-plus怎么也找不到AutoGenerator类,这里标注一下,提醒自己。
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-generator -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<!-- freemarker模板引擎依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
下面是demo代码,需要注意的东西都写在注释里了,如果觉得不够详细,留言我再补充。
public class MybatisPlusGenerator {
/**
* 子服务模块名
* 项目的文件夹名,如果是多个子模块,则需要针对不同的模块进行修改
* 例如parent下有user、email两个模块,则生成代码时需要改成user或者email模块的文件夹名
* 如果是springboot initualizr生成的单体项目则直接留空即可
*/
private static final String CMS_MODULE_NAME = "/email-delivery-platform";
/**
* 父包名
*/
private static final String CMS_PACKAGE_CONFIG_PARENT = "com.genius.mail";
/**
* 修改路径和要反向生成的表后,直接运行即可。
*/
public static void main(String[] args) {
// tables为空表示生成全部表,最好只有初始化时设为空,之后请务必填写要操作的表,不然会覆盖其他业务已有内容
String[] tables = {""};
// 是否只生成entity和xml,要生成Controller、Service、Mapper改成:false
boolean isOnlyModel = false;
// 作者署名
String author = "";
// 执行代码生成
generator(CMS_MODULE_NAME, CMS_PACKAGE_CONFIG_PARENT, tables, isOnlyModel, author);
}
/**
* MySQL 反向生成
*
* @param moduleName 模块名,用于构造生成根路径位置
* @param packageConfigParent 父包名,用于指定生成类的父包位置
* @param tableNames 需要生成的表数组
* @param isOnlyModel 是否只生成entity和xml
* @param author 作者署名
*/
private static void generator(String moduleName, String packageConfigParent, String[] tableNames, boolean
isOnlyModel, String author) {
AutoGenerator mpg = new AutoGenerator();
// 项目根路径
String projectPath = System.getProperty("user.dir") + moduleName;
// 选择 freemarker 引擎,不设置默认 Veloctiy
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 1. 全局配置
GlobalConfig gc = new GlobalConfig();
// 输出位置
gc.setOutputDir(projectPath + "/src/main/java");
// 添加作者
gc.setAuthor(author);
// 覆盖同名文件
gc.setFileOverride(true);
// 添加swagger
gc.setSwagger2(false);
// 不需要ActiveRecord特性的改为false
gc.setActiveRecord(true);
// XML 二级缓存关闭
gc.setEnableCache(false);
// XML ResultMap
gc.setBaseResultMap(true);
// XML columList
gc.setBaseColumnList(true);
//是否生成 kotlin 代码
gc.setKotlin(false);
// 自定义文件命名,注意 %s 会自动填充表实体属性!
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setControllerName("%sController");
mpg.setGlobalConfig(gc);
// 2. 数据源配置
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(){
// 自定义数据库表字段类型转换【可选】
public DbColumnType processTypeConvert(String fieldType) {
System.out.println("转换类型:" + fieldType);
// 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。
return super.processTypeConvert(fieldType);
}
});*/
mpg.setDataSource(dsc);
// 3.策略配置
// 自定义需要填充的字段 数据库中的字段
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();
// 添加默认填充字段注解:@TableField(fill = FieldFill.INSERT_UPDATE) | @TableField(fill = FieldFill.INSERT)
strategy.setLogicDeleteFieldName("dr");
strategy.setTableFillList(tableFillList);
// 下划线转驼峰命名
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// 实体添加Lombok
strategy.setEntityLombokModel(true);
// 使用rest风格Controller
strategy.setRestControllerStyle(true);
// 去除表前缀
// strategy.setTablePrefix(new String[]{"sys_"});
// 全局大写命名 ORACLE 注意
// strategy.setCapitalMode(true);
// 此处可以修改为您的表前缀
// 表名生成策略:下划线变驼峰
// 需要生成的表,注释掉生成全部表
if (ArrayUtils.isNotEmpty(tableNames)) {
strategy.setInclude(tableNames);
}
// 排除生成的表
//strategy.setExclude(new String[]{"sys_test"});
// 自定义实体父类
// strategy.setSuperEntityClass("com.yonyou.mphplus.BaseEntity");
// 自定义实体父类的 公共字段
// strategy.setSuperEntityColumns(new String[] { "creator", "create_time" });
// 自定义 mapper 父类
// strategy.setSuperMapperClass("com.yonyou.mphplus.BaseMapper");
// 自定义 service 父类
// strategy.setSuperServiceClass("com.yonyou.mphplus.BaseService");
// 自定义 service 实现类父类
// strategy.setSuperServiceImplClass("com.yonyou.mphplus.BaseServiceImpl");
// 自定义 controller 父类
// strategy.setSuperControllerClass("com.yonyou.mphplus.BaseController");
// 【实体】是否生成字段常量(默认 false)
// public static final String ID = "test_id";
//strategy.setEntityColumnConstant(true);
// 【实体】是否为构建者模型(默认 false)
// public User setName(String name) {this.name = name; return this;}
//strategy.setEntityBuilderModel(true);
// 自定义需要填充的字段
// List<TableFill> tableFillList = new ArrayList<>();
// tableFillList.add(new TableFill("ASDD_SS", FieldFill.INSERT_UPDATE));
// strategy.setTableFillList(tableFillList);
mpg.setStrategy(strategy);
// 4. 包配置
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);
/* // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】 ${cfg.abc}
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
Map<String, Object> map = new HashMap<>(16);
map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
this.setMap(map);
}
};
// 自定义 xxListIndex.html 生成
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/list.html.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return "/src/main/resources/static/" + tableInfo.getEntityName() + "ListIndex.html";
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);*/
// 5. 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
}
};
// 自定义输出配置:输出xml到/resources/mapper
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo t) {
// 自定义输出文件名
return projectPath + "/src/main/resources/mapper/" + t.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 6. 配置模板,不输出xml到src
TemplateConfig tc = new TemplateConfig();
// 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
// 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
// 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");
// // 如上任何一个模块如果设置 空 或 null 将不生成该模块。后续根据需要设置,防止代码覆盖
// 不输出xml到src
tc.setXml(null);
// 是否只生成实体和xml
if (isOnlyModel) {
tc.setController(null);
tc.setService(null);
tc.setServiceImpl(null);
tc.setMapper(null);
}
mpg.setTemplate(tc);
// 执行生成
mpg.execute();
// 打印注入设置【可无】
// System.err.println(mpg.getCfg().getMap().get("abc"));
}
}