SpringBoot MyBatisPlus 定製化模板

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章