SpringBoot MyBatisPlus 定制化模板

    技术2022-08-01  68

    1.首先看下生成的最终效果 1.1 Controller package com.scsiot.smartcity.smarthome.controller; import org.springframework.web.bind.annotation.*; import lombok.extern.slf4j.Slf4j; import com.scsiot.smartcity.common.util.result.JsonResult; import com.scsiot.smartcity.smarthome.service.IConfigService; import com.scsiot.smartcity.smarthome.entity.Config; import com.baomidou.mybatisplus.core.metadata.IPage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; /** * <p> * 系统配置 前端控制器 * </p> * * @author liuzhen * @since 2020-07-02 */ @Slf4j @RestController @RequestMapping("/config") public class ConfigController { @Autowired private IConfigService configService; /** * 查询 系统配置 分页列表 * @param config 实体 * @return ResponseInfo */ @PostMapping("/queryList") public JsonResult<IPage< Config>> queryList(@RequestBody Config config,Integer pageNum,Integer pageSize){ return configService.queryByPage(config,pageNum,pageSize); } /** * 查询单个数据 系统配置 详情 * * @param config 条件查询数据 * @return JsonResult */ @GetMapping("/queryByEntity") public JsonResult<Config> queryByEntity(Config config) { return configService.queryByEntity(config); } /** * 新增 系统配置 * * @param config 请求参数 * @return JsonResult */ @PostMapping("/add") public JsonResult<Boolean> add(@Validated @RequestBody Config config) { return configService.add(config); } /** * 删除 系统配置 * * @param id 主键id * @return JsonResult */ @DeleteMapping("/{id}") public JsonResult<Boolean> delete(@PathVariable Long id) { return configService.delete(id); } } 1.2 service package com.scsiot.smartcity.smarthome.service; import com.scsiot.smartcity.smarthome.entity.Config; import com.baomidou.mybatisplus.extension.service.IService; import com.scsiot.smartcity.common.util.result.JsonResult; import com.baomidou.mybatisplus.core.metadata.IPage; /** * <p> * 系统配置 服务类 * </p> * * @author liuzhen * @since 2020-07-02 */ public interface IConfigService extends IService<Config> { /** * 分页查询 * @param config 请求参数 * @param pageNum 页码 * @param pageSize 页数大小 * @return JsonResult 分页列表 */ JsonResult<IPage<Config>> queryByPage(Config config, Integer pageNum, Integer pageSize); /** * 查询单个数据 系统配置 详情 * * @param config 条件查询数据 * @return JsonResult */ JsonResult<Config> queryByEntity(Config config); /** * 新增 系统配置 * * @param config 请求参数 * @return JsonResult */ JsonResult<Boolean> add(Config config); /** * 修改 系统配置 * * @param config 请求参数 * @return JsonResult */ JsonResult<Boolean> update(Config config); /** * 删除 系统配置 * * @param id 主键id * @return JsonResult */ JsonResult<Boolean> delete(Long id); } 1.3 ServiceImpi package com.scsiot.smartcity.smarthome.service.serviceImpl; import com.baomidou.mybatisplus.core.metadata.IPage; import com.scsiot.smartcity.smarthome.entity.Config; import com.scsiot.smartcity.smarthome.mapper.ConfigMapper; import com.scsiot.smartcity.smarthome.service.IConfigService; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; 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> * 系统配置 服务实现类 * </p> * * @author liuzhen * @since 2020-07-02 */ @Service @Slf4j public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements IConfigService { /** * 分页查询 * @param config 请求参数 * @param pageNum 页码 * @param pageSize 页数大小 * @return JsonResult分页列表 */ @Override public JsonResult<IPage<Config>> queryByPage(Config config, Integer pageNum, Integer pageSize){ //获取公共查询 LambdaQueryWrapper<Config> queryWrapper =baseQuery(config); //排序 queryWrapper.orderByDesc(Config::getId); //分页查询 Page<Config> pages = new Page<Config>(pageNum == null ? 1 : pageNum,pageSize == null ? 15 : pageSize); return JsonResult.successData(super.baseMapper.selectPage(pages, queryWrapper)); } /** * 基础查询---匹配是否为空,不为空,则录入数据,为空则不加入查询 * @param config 请求参数 * @return LambdaQueryWrapper 封装好的数据 */ public LambdaQueryWrapper<Config> baseQuery(Config config){ LambdaQueryWrapper<Config> queryWrapper = new LambdaQueryWrapper<>(); if (config.getId() != null ) { queryWrapper.eq(Config::getId,config.getId()); } if (!StringUtils.isNotEmpty(config.getVariable())) { queryWrapper.eq(Config::getVariable,config.getVariable()); } if (!StringUtils.isNotEmpty(config.getValue())) { queryWrapper.eq(Config::getValue,config.getValue()); } if (config.getSetTime() != null ) { queryWrapper.eq(Config::getSetTime,config.getSetTime()); } if (!StringUtils.isNotEmpty(config.getSetBy())) { queryWrapper.eq(Config::getSetBy,config.getSetBy()); } return queryWrapper; } /** * 查询单个数据 系统配置 详情 * * @param config 条件查询数据 * @return JsonResult */ @Override public JsonResult<Config> queryByEntity(Config config){ //获取公共查询 LambdaQueryWrapper<Config> queryWrapper =baseQuery(config); Config configDB =super.getOne(queryWrapper); if(configDB == null){ return JsonResult.ErrorMessage("该数据不存在!请核对后重试"); } return JsonResult.successData(configDB); } /** * 新增或者修改 系统配置 * * @param config 请求参数 * @return JsonResult */ @Transactional(rollbackFor = Exception.class) @Override public JsonResult<Boolean> add(Config config){ super.save(config); return JsonResult.successData(); } /** * 修改 系统配置 * * @param config 请求参数 * @return JsonResult */ @Transactional(rollbackFor = Exception.class) @Override public JsonResult<Boolean> update(Config config){ if(config.getId() == null){ return JsonResult.ErrorMessage("ID不能为空!"); } super.updateById(config); return JsonResult.successData(); } /** * 删除 系统配置 * * @param id 主键id * @return JsonResult */ @Override @Transactional(rollbackFor = Exception.class) public JsonResult<Boolean> delete(Long id){ super.removeById(id); return JsonResult.successData(); } } 2.首先添加mybatis plus pom文件 <!-- mybatisplus与springboot整合--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.3</version> </dependency> <!-- 模板引擎mybatis plus 生成代码用 --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.0</version> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.20</version> </dependency>

     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); } } #end

     service.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); } #end

    serviceImpl.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

     

    Processed: 0.015, SQL: 9