简单封装mybatis-plus代码生成工具供自己使用
主要使用MyBatis-Plus提供的generator代码生成器根据数据表生成MVC模式下的Controller、Service、Mapper及Mapper XML文件等代码,简化开发中代码的编写;
参考MyBatis-Plus官方文档,链接: mybatis-plus
环境版本
JDK1.8
mybatis-plus-generator 3.4.1
Maven引入依赖
<dependencies>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<!-- mybatis-plus代码生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<!-- freemarker代码生成器模板 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
</dependencies>
code-generator工具编写
/**
* 根据数据表 生成controller、service、serviceImpl、mapper、domain、mapper.xml
* 修改 COMMON_PATH 自定义包名
* 修改 SQL_URL 数据库地址
* 修改 SQL_USER 数据库账号
* 修改 SQL_PASSWORD 数据库密码
*/
public class CodeGenerator {
private static final String COMMON_PATH = "";
private static final String SQL_URL = "";
private static final String SQL_USER = "";
private static final String SQL_PASSWORD = "";
private static final String ignoreTablePrefix = ""; //需要忽略的表前缀
private static final String SRC_PATH = System.getProperty("user.dir") + "/src/main/java";
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
initMenu();
String sign = scanner("选项");
switch (sign) {
case "1":
initConfig(true);
break;
case "2":
initConfig(false);
break;
default:
System.exit(1);
}
}
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入" + tip + ":");
if (scanner.hasNext()) {
String ipt = scanner.next();
if (ipt != null && ipt.length() > 0) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void initMenu() {
System.out.println("------------------- MyBatis-Plus 代码生成器 -------------------");
System.out.println("|\t\t\t\t1.不包含controller;service\t\t\t\t\t|");
System.out.println("|\t\t\t\t2.包含controller;service\t\t\t\t\t\t|");
System.out.println("-------------------------------------------------------------");
}
public static void initConfig(boolean isIgnore) throws NoSuchFieldException, IllegalAccessException {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(SRC_PATH);
gc.setFileOverride(true);
gc.setOpen(true);
gc.setBaseResultMap(true);
gc.setBaseColumnList(true);
if (!isIgnore) {
gc.setControllerName("%sController");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
}
gc.setEntityName("%s");
gc.setXmlName("%sMapper");
gc.setMapperName("%sMapper");
gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
gc.setAuthor("author");
gc.setOpen(false);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig().setDbQuery(new MySqlQuery() {
/**
* 重写父类预留查询自定义字段<br>
* 这里查询的 SQL 对应父类 tableFieldsSql 的查询字段,默认不能满足你的需求请重写它<br>
* 模板中调用: table.fields 获取所有字段信息,
* 然后循环字段获取 field.customMap 从 MAP 中获取注入字段如下 NULL 或者 PRIVILEGES
*/
@Override
public String[] fieldCustom() {
return new String[]{"NULL", "PRIVILEGES"};
}
});
dsc.setUrl("jdbc:mysql://" + SQL_URL + "?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername(SQL_USER);
dsc.setPassword(SQL_PASSWORD);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
mpg.setPackageInfo(pc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
if (null != ignoreTablePrefix) strategy.setTablePrefix(ignoreTablePrefix);
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 写于父类中的公共字段
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
if (!isIgnore) strategy.setControllerMappingHyphenStyle(true);
strategy.setEntityColumnConstant(true);
strategy.setEntityBuilderModel(true);
strategy.setEntityTableFieldAnnotationEnable(true);
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
//自定义文件生成路径,包路径
//这里调用customPackagePath方法,使用可以自己在内部灵活配置路径
//如果不调用该方法、就会使用MyBatis-Plus默认的文件生成路径和包路径生成文件、但可以使用上面的PackageConfig做一些简单的配置
customPackagePath(pc, mpg, isIgnore);
mpg.execute();
}
/**
* 自定义包路径,文件生成路径,这边配置更灵活
* 虽然也可以使用InjectionConfig设置FileOutConfig的方式设置路径
* 这里直接使用Map方式注入ConfigBuilder配置对象更加直观
*/
public static void customPackagePath(PackageConfig pc, AutoGenerator mpg, boolean isIgnore) throws NoSuchFieldException, IllegalAccessException {
String moduleName = pc.getModuleName();
/**
* packageInfo配置controller、service、serviceImpl、entity、mapper等文件的包路径
* 这里包路径可以根据实际情况灵活配置
*/
Map<String, String> packageInfo = new HashMap<>();
if (!isIgnore) {
packageInfo.put(ConstVal.CONTROLLER, COMMON_PATH + ".controller." + moduleName);
packageInfo.put(ConstVal.SERVICE, COMMON_PATH + ".service." + moduleName);
packageInfo.put(ConstVal.SERVICE_IMPL, COMMON_PATH + ".service.impl." + moduleName);
}
packageInfo.put(ConstVal.ENTITY, COMMON_PATH + ".domain." + moduleName);
packageInfo.put(ConstVal.MAPPER, COMMON_PATH + ".mapper." + moduleName);
/**
* pathInfo配置controller、service、serviceImpl、entity、mapper、mapper.xml等文件的生成路径
* srcPath也可以更具实际情况灵活配置
* 后面部分的路径是和上面packageInfo包路径对应的源码文件夹路径
* 这里你可以选择注释其中某些路径,可忽略生成该类型的文件,例如:注释掉下面pathInfo中Controller的路径,就不会生成Controller文件
*/
Map<String, String> pathInfo = new HashMap<>();
if (!isIgnore) {
pathInfo.put(ConstVal.CONTROLLER_PATH, SRC_PATH + StringPool.SLASH + packageInfo.get(ConstVal.CONTROLLER).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
pathInfo.put(ConstVal.SERVICE_PATH, SRC_PATH + StringPool.SLASH + packageInfo.get(ConstVal.SERVICE).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
pathInfo.put(ConstVal.SERVICE_IMPL_PATH, SRC_PATH + StringPool.SLASH + packageInfo.get(ConstVal.SERVICE_IMPL).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
}
pathInfo.put(ConstVal.ENTITY_PATH, SRC_PATH + StringPool.SLASH + packageInfo.get(ConstVal.ENTITY).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
pathInfo.put(ConstVal.MAPPER_PATH, SRC_PATH + StringPool.SLASH + packageInfo.get(ConstVal.MAPPER).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
pathInfo.put(ConstVal.XML_PATH, System.getProperty("user.dir") + "/src/main/resources/mapper/" + moduleName);
pc.setPathInfo(pathInfo);
/**
* 创建configBuilder对象,传入必要的参数
* 将以上的定义的包路径packageInfo配置到赋值到configBuilder对象的packageInfo属性上
* 因为packageInfo是私有成员变量,也没有提交提供公共的方法,所以使用反射注入
* 为啥要这么干,看源码去吧
*/
ConfigBuilder configBuilder = new ConfigBuilder(mpg.getPackageInfo(), mpg.getDataSource(), mpg.getStrategy(), mpg.getTemplate(), mpg.getGlobalConfig());
Field packageInfoField = configBuilder.getClass().getDeclaredField("packageInfo");
packageInfoField.setAccessible(true);
packageInfoField.set(configBuilder, packageInfo);
/**
* 设置配置对象
*/
mpg.setConfig(configBuilder);
}
}
直接运行使用即可,这是我自己开发时使用的(支持多表),必定根据表生成Mapper,Mapper XML和domain实体,因为有时我只需要这三个,Service和Controller自己定义,所以我加了选项,也可按需修改
如有问题还请大佬们指正