// 1. 创建代码生成器对象
AutoGenerator mpg = new AutoGenerator();
// 2. 设置数据源
DataSourceConfig dataSource = new DataSourceConfig();
dataSource.setUrl("jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT");
dataSource.setUsername("root");
dataSource.setPassword("");
dataSource.setDriverName("com.mysql.cj.jdbc.Driver");
mpg.setDataSource(dataSource);
// 4. 配置包
PackageConfig pc = new PackageConfig();
pc.setParent("com.itcast.base"); // 设置父包名
pc.setModuleName("edu"); // 设置父包模块名
pc.setEntity("entity");
pc.setService("service");
// pc.setServiceImpl("service.impl");
pc.setController("controller");
pc.setMapper("mapper");
// pc.setXml("mapper.xml");
mpg.setPackageInfo(pc);
// 3. 数据表配置
StrategyConfig strategy = new StrategyConfig();
strategy.setEntityLombokModel(true); // 设置Lombok的使用
strategy.setEntityBooleanColumnRemoveIsPrefix(true); // 设置表字段是否移除is前缀
strategy.setRestControllerStyle(true); // 生成RestController控制器
strategy.setControllerMappingHyphenStyle(true); // url驼峰连接字符
strategy.setEntityTableFieldAnnotationEnable(true); // 是否生成实体时,生成字段注解
strategy.setVersionFieldName("version"); // 乐观锁设置
strategy.setTablePrefix(pc.getModuleName() + "_");
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setLogicDeleteFieldName("is_deleted"); // 逻辑删除属性名称
// 设置自动填充字段
strategy.setTableFillList(Arrays.asList(new TableFill("create_time", FieldFill.INSERT),
new TableFill("update_time", FieldFill.INSERT_UPDATE)));
mpg.setStrategy(strategy);
// 5. 配置模板引擎
String templatePath = "/templates/mapper.xml.ftl";
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 6. 全局配置
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java"); // 获取当前项目路径
globalConfig.setFileOverride(true); // 覆盖文件
globalConfig.setOpen(false); // 打开目录
globalConfig.setAuthor("小新");
//globalConfig.setSwagger2(true); // 开启Swagger2模式
globalConfig.setEntityName("%s"); // 提示类,命名方式
globalConfig.setMapperName("%sMapper");
// globalConfig.setXmlName("%sMapper.xml");
globalConfig.setServiceName("%sService");
globalConfig.setServiceImplName("%sServiceImpl");
globalConfig.setControllerName("%sControlller");
globalConfig.setDateType(DateType.ONLY_DATE);
mpg.setTemplateEngine(new FreemarkerTemplateEngine()); // 指定使用的模板引擎
mpg.setGlobalConfig(globalConfig);
mpg.execute();// 开始生成
System.out.println(pc.getParent());