3.编写代码生成类,主要是调用mybatisPlus 已经成型的API,通过配置要生成的表,和包路径等信息.生成表结构
package com.scsiot.smartcity; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert; import com.baomidou.mybatisplus.generator.config.rules.IColumnType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; /** * <p> * 代码生成器演示 * </p> */ public class MpGenerator { /** * 代码生成地址 */ final static String outputDirPath = "D://"; /** * 作者 */ final static String author = "liuzhen"; /** * 文件是否覆盖 */ final static boolean fileOverride=true; /** * 表名前缀 */ final static String[] tablePrefix=new String[]{"sys_"}; /** * 数据库配置 */ final static String driverName="com.mysql.cj.jdbc.Driver"; final static String userName="root"; final static String password="123456"; final static String url="jdbc:mysql://localhost:3306/sys?characterEncoding=utf8&serverTimezone=UTC"; /** * 需要生成的表 */ final static String includeTables[] =new String[]{"sys_config"}; /** * 排除的表 */ final static String excludeTables[] =new String[]{}; final static String packetName="com.scsiot.smartcity.smarthome"; /** * <p> * MySQL 生成演示 * </p> */ public static void main(String[] args) { AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); gc.setOutputDir(outputDirPath); gc.setAuthor(author); gc.setFileOverride(fileOverride); //是否覆盖 gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false gc.setEnableCache(false);// XML 二级缓存 gc.setBaseResultMap(true);// XML ResultMap gc.setBaseColumnList(true);// XML columList gc.setOpen(false); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setTypeConvert(new MySqlTypeConvert(){ // 自定义数据库表字段类型转换【可选】 public IColumnType processTypeConvert(String fieldType) { System.out.println("转换类型:" + fieldType); // 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。 return super.processTypeConvert(gc,fieldType); } }); dsc.setDriverName(driverName); dsc.setUsername(userName); dsc.setPassword(password); dsc.setUrl(url); mpg.setDataSource(dsc); // 策略配置 StrategyConfig strategy = new StrategyConfig(); // strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意 strategy.setTablePrefix(tablePrefix);// 此处可以修改为您的表前缀 strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略 if(includeTables.length >0) { strategy.setInclude(includeTables); // 需要生成的表 } if(excludeTables.length >0) { strategy.setExclude(excludeTables); // 排除生成的表 } strategy.setRestControllerStyle(true); strategy.setEntityBuilderModel(false); mpg.setStrategy(strategy); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent(packetName); pc.setController("controller"); pc.setEntity("entity"); pc.setMapper("mapper"); pc.setService("service"); pc.setServiceImpl("service.serviceImpl"); mpg.setPackageInfo(pc); // 关闭默认 xml 生成,调整生成 至 根目录 TemplateConfig tc = new TemplateConfig(); tc.setXml(null); mpg.setTemplate(tc); // 执行生成 mpg.execute(); // 打印注入设置【可无】 System.err.println("代码生成成功!"); } }4.但是我们发现,通过配置这些已经生成很完善的代码了.但是我们想更进一步的修改.减少后期开发量.比如,增删改查,从Controller到dto打通,生成既可以使用.分页查询,直接交互给前端.比如后期的 前端页面.
目前生成不包含前端. 下一期将生成固定的VUE或者基于easyUI界面.
通过跟踪代码,我们发现,生成代码模板放在MybatisPlus 包的Resource里面.
我们将这几个文件拷贝下来,放到我们项目的 static/templates/ 文件夹下面
接下来,就是我们需要的修改的模板,分别是 controller.java.vm ,service.java.vm ,serviceImpl.java.vm
里面定义的参数很多.我们只要按着我们项目现有的架构,一一调整下生成的类,引入的包
.controller.java.vm 模板修改如下
package ${package.Controller}; import org.springframework.web.bind.annotation.*; import lombok.extern.slf4j.Slf4j; import com.scsiot.smartcity.common.util.result.JsonResult; import ${package.Service}.${table.serviceName}; import ${package.Entity}.${entity}; import com.baomidou.mybatisplus.core.metadata.IPage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; #if(${restControllerStyle}) #else import org.springframework.stereotype.Controller; #end #if(${superControllerClassPackage}) import ${superControllerClassPackage}; #end /** * <p> * $!{table.comment} 前端控制器 * </p> * * @author ${author} * @since ${date} */ @Slf4j #if(${restControllerStyle}) @RestController #else @Controller #end @RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end") #if(${kotlin}) @Slf4j class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end #else #if(${superControllerClass}) public class ${table.controllerName} extends ${superControllerClass} { #else public class ${table.controllerName} { #end @Autowired private ${table.serviceName} ${table.entityPath}Service; /** * 查询 $!{table.comment} 分页列表 * * * @param ${table.entityPath} 实体 * @return ResponseInfo */ @PostMapping("queryList") public JsonResult<IPage< ${entity}>> queryList(@RequestBody ${entity} ${table.entityPath},Integer pageNum,Integer pageSize){ return ${table.entityPath}Service.queryByPage(${table.entityPath},pageNum,pageSize); } /** * 查询单个数据 $!{table.comment} 详情 * * @param ${table.entityPath} 条件查询数据 * @return JsonResult */ @GetMapping("/queryByEntity") public JsonResult<${entity}> queryByEntity(${entity} ${table.entityPath}) { return ${table.entityPath}Service.queryByEntity(${table.entityPath}); } /** * 新增 $!{table.comment} * * @param ${table.entityPath} 请求参数 * @return JsonResult */ @PostMapping("/add") public JsonResult<Boolean> add(@Validated @RequestBody ${entity} ${table.entityPath}) { return ${table.entityPath}Service.add(${table.entityPath}); } /** * 新增 $!{table.comment} * * @param ${table.entityPath} 请求参数 * @return JsonResult */ @PostMapping("/update") public JsonResult<Boolean> update(@Validated @RequestBody ${entity} ${table.entityPath}) { return ${table.entityPath}Service.update(${table.entityPath}); } /** * 删除 $!{table.comment} * * @param id 主键id * @return JsonResult */ @DeleteMapping("/{id}") public JsonResult<Boolean> delete(@PathVariable Long id) { return ${table.entityPath}Service.delete(id); } } #endservice.java.vm 修改如下
package ${package.Service}; import ${package.Entity}.${entity}; import ${superServiceClassPackage}; import com.scsiot.smartcity.common.util.result.JsonResult; import com.baomidou.mybatisplus.core.metadata.IPage; /** * <p> * $!{table.comment} 服务类 * </p> * * @author ${author} * @since ${date} */ #if(${kotlin}) interface ${table.serviceName} : ${superServiceClass}<${entity}> #else public interface ${table.serviceName} extends ${superServiceClass}<${entity}> { /** * 分页查询 * @param ${table.entityPath} 请求参数 * @param pageNum 页码 * @param pageSize 页数大小 * @return JsonResult 分页列表 */ JsonResult<IPage<${entity}>> queryByPage(${entity} ${table.entityPath},Integer pageNum,Integer pageSize); /** * 查询单个数据 $!{table.comment} 详情 * * @param ${table.entityPath} 条件查询数据 * @return JsonResult */ JsonResult<${entity}> queryByEntity(${entity} ${table.entityPath}); /** * 新增 $!{table.comment} * * @param ${table.entityPath} 请求参数 * @return JsonResult */ JsonResult<Boolean> add(${entity} ${table.entityPath}); /** * 修改 $!{table.comment} * * @param ${table.entityPath} 请求参数 * @return JsonResult */ JsonResult<Boolean> update(${entity} ${table.entityPath}); /** * 删除 $!{table.comment} * * @param id 主键id * @return JsonResult */ JsonResult<Boolean> delete(Long id); } #endserviceImpl.java.vm 配置如下
package ${package.ServiceImpl}; import ${package.Entity}.${entity}; import ${package.Mapper}.${table.mapperName}; import ${package.Service}.${table.serviceName}; import org.springframework.stereotype.Service; import ${superServiceImplClassPackage}; import org.apache.commons.lang3.StringUtils; import com.scsiot.smartcity.common.util.result.JsonResult; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import lombok.extern.slf4j.Slf4j; import org.springframework.transaction.annotation.Transactional; /** * <p> * $!{table.comment} 服务实现类 * </p> * * @author ${author} * @since ${date} */ @Service @Slf4j #if(${kotlin}) open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} { } #else public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} { /** * 分页查询 * @param ${table.entityPath} 请求参数 * @param pageNum 页码 * @param pageSize 页数大小 * @return JsonResult分页列表 */ @Override public JsonResult<IPage<${entity}>> queryByPage(${entity} ${table.entityPath},Integer pageNum,Integer pageSize){ //获取公共查询 LambdaQueryWrapper<${entity}> queryWrapper =baseQuery(${table.entityPath}); //排序 queryWrapper.orderByDesc(${entity}::getId); //分页查询 Page<${entity}> pages = new Page<${entity}>(pageNum == null ? 1 : pageNum,pageSize == null ? 15 : pageSize); return JsonResult.successData(super.baseMapper.selectPage(pages, queryWrapper)); } /** * 基础查询---匹配是否为空,不为空,则录入数据,为空则不加入查询 * @param ${table.entityPath} 请求参数 * @return LambdaQueryWrapper 封装好的数据 */ public LambdaQueryWrapper<${entity}> baseQuery(${entity} ${table.entityPath}){ LambdaQueryWrapper<${entity}> queryWrapper = new LambdaQueryWrapper<>(); ## ---------- BEGIN 字段循环遍历 ---------- #foreach($field in ${table.fields}) #if(${field.propertyType.equals("String")}) if (!StringUtils.isNotEmpty(${table.entityPath}.get${field.capitalName}())) { queryWrapper.eq(${entity}::get${field.capitalName},${table.entityPath}.get${field.capitalName}()); } #else if (${table.entityPath}.get${field.capitalName}() != null ) { queryWrapper.eq(${entity}::get${field.capitalName},${table.entityPath}.get${field.capitalName}()); } #end #end ## ---------- END 字段循环遍历 ---------- return queryWrapper; } /** * 查询单个数据 $!{table.comment} 详情 * * @param ${table.entityPath} 条件查询数据 * @return JsonResult */ @Override public JsonResult<${entity}> queryByEntity(${entity} ${table.entityPath}){ //获取公共查询 LambdaQueryWrapper<${entity}> queryWrapper =baseQuery(${table.entityPath}); ${entity} ${table.entityPath}DB =super.getOne(queryWrapper); if(${table.entityPath}DB == null){ return JsonResult.ErrorMessage("该数据不存在!请核对后重试"); } return JsonResult.successData(${table.entityPath}DB); } /** * 新增或者修改 $!{table.comment} * * @param ${table.entityPath} 请求参数 * @return JsonResult */ @Transactional(rollbackFor = Exception.class) @Override public JsonResult<Boolean> add(${entity} ${table.entityPath}){ super.save(${table.entityPath}); return JsonResult.successData(); } /** * 修改 $!{table.comment} * * @param ${table.entityPath} 请求参数 * @return JsonResult */ @Transactional(rollbackFor = Exception.class) @Override public JsonResult<Boolean> update(${entity} ${table.entityPath}){ if(${table.entityPath}.getId() == null){ return JsonResult.ErrorMessage("ID不能为空!"); } super.updateById(${table.entityPath}); return JsonResult.successData(); } /** * 删除 $!{table.comment} * * @param id 主键id * @return JsonResult */ @Override @Transactional(rollbackFor = Exception.class) public JsonResult<Boolean> delete(Long id){ super.removeById(id); return JsonResult.successData(); } } #end