詳解使用Mybatis-plus + velocity模板生成自定義的代碼

pom.xml文件的配置

<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-boot-starter</artifactId>
  <version>3.3.0</version>
</dependency>
<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-generator</artifactId>
  <version>3.1.0</version>
</dependency>

<!-- 代碼生成器模板 -->
<dependency>
  <groupId>org.apache.velocity</groupId>
  <artifactId>velocity</artifactId>
  <version>1.7</version>
</dependency>

CodeGenerator配置文件

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import lombok.extern.java.Log;

/**
 * 代碼生成器
 */
@Log
public class CodeGenerator {

 //項目存儲位置
 public static String PROJECT_GENERATE_DISK = "E:\\";
 //包名
 public static String PARENT_PACKAGE_NAME = "com";
 //包名
 public static String PACKAGE_NAME = "rent.security";
 //數據庫地址
 public static String DB_URL = "jdbc:mysql://localhost:3306/mp?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC";
 //數據庫實例名
 public static String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
 //數據庫用戶
 public static String USER = "root";
 //數據庫密碼
 public static String PASSWORD = "root";
 //數據庫schema
 public static String SCHEMA = "mp";
 //要查詢的表名
 public static String TABLE_NAMES = "sys_role_menu";
 //創建人
 public static String AUTHOR = "jmm";
 //是否強制帶上註解
 public static boolean ENABLE_TABLE_FIELD_ANNOTATION = false;
 //生成的註解帶上IdType類型
 public static IdType TABLE_IDTYPE = null;
 //生成的Service 接口類名是否以I開頭 默認是以I開頭 user表 -> IUserService, UserServiceImpl
 public static boolean SERVICE_CLASS_NAME_START_WITHI = false;

 /**
 * 全局配置
 */
 private static GlobalConfig GlobalGenerate() {
 GlobalConfig config = new GlobalConfig();
 config.setActiveRecord(false)// 不需要ActiveRecord特性的請改為false
  .setIdType(TABLE_IDTYPE)
  .setEnableCache(false)// XML 二級緩存
  .setAuthor(AUTHOR)
  .setBaseResultMap(true)// XML ResultMap
  .setBaseColumnList(false)// XML columList
  .setOutputDir(PROJECT_GENERATE_DISK + "\\java" )
  .setFileOverride(true)
  .setControllerName("%sController" );//自定義文件命名,註意 %s 會自動填充表實體屬性!

 if (!SERVICE_CLASS_NAME_START_WITHI) {
  config.setServiceName("%sService" );
 }
 return config;
 }

 /**
 * 數據源配置
 */
 private static DataSourceConfig DaoSourceGenerate() {
 DataSourceConfig dataSourceConfig = new DataSourceConfig();
 DbType type = DbType.MYSQL;
 dataSourceConfig.setDbType(type)//數據庫類型
  .setUrl(DB_URL)//數據庫地址
  .setUsername(USER)//數據庫用戶名
  .setPassword(PASSWORD)//數據庫密碼
  .setDriverName(DRIVER_CLASS_NAME)//實例名
  .setSchemaName(SCHEMA);
 return dataSourceConfig;
 }

 /**
 * 策略配置
 */
 private static StrategyConfig StrategyGenerate() {
 StrategyConfig strategyConfig = new StrategyConfig();
 strategyConfig.setVersionFieldName("version" )
  .setCapitalMode(true)// 全局大寫命名 ORACLE 註意
  .setEntityLombokModel(false)
  .setNaming(NamingStrategy.underline_to_camel)// 表名生成策略
  .entityTableFieldAnnotationEnable(ENABLE_TABLE_FIELD_ANNOTATION)
  .setInclude(TABLE_NAMES)//修改替換成你需要的表名,多個表名傳數組
  .setEntityColumnConstant(true)// 【實體】是否生成字段常量(默認 false)public static final String ID = "test_id";
  .setEntityBuilderModel(true);// 【實體】是否為構建者模型(默認 false)public User setName(String name) {this.name = name; return this;}
 return strategyConfig;
 }

 /**
 * 自定義模板配置
 */
 private static TemplateConfig TemplateGenerate() {
 TemplateConfig templateConfig = new TemplateConfig()
  .setController("templates/java/controller.java" )
  .setService("templates/java/service.java" )
  .setServiceImpl("templates/java/serviceImpl.java" )
  .setMapper("templates/java/mapper.java" );
 return templateConfig;
 }

 private static final String MODULE_NAME = "sysRoleMenu";

 private static final String CLASS_NAME = "SysRoleMenu";

 private static final String class_name = "sysRoleMenu";

 /**
 * 自定義文件及key
 */
 private static InjectionConfig FileGenerate() {
 InjectionConfig injectionConfig = new InjectionConfig() {
  @Override
  public void initMap() {//自定義參數
  Map<String, Object> map = new HashMap<>();
  //這些自定義的值在vm模板的語法是通過${cfg.xxx}來調用的。
  map.put("moduleName", MODULE_NAME);
  map.put("ClassName", CLASS_NAME);
  map.put("className", class_name);
  map.put("packageName", PARENT_PACKAGE_NAME + "." + PACKAGE_NAME);
  map.put("author", AUTHOR);
  map.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
  this.setMap(map);
  }
 };
 return injectionConfig;
 }

 /**
 * 包配置
 */
 public static PackageConfig PackageGenerate() {
 PackageConfig pc = new PackageConfig().setParent("com" )
  .setModuleName(PACKAGE_NAME)
  .setController("controller")
  .setEntity("domain")
  .setMapper("dao")
  .setXml("mapper");
 return pc;
 }

 public static void main(String[] args) {
 //全局配置
 GlobalConfig config = GlobalGenerate();
 //配置數據源
 DataSourceConfig dataSourceConfig = DaoSourceGenerate();
 //配置策略
 StrategyConfig strategyConfig = StrategyGenerate();
 //配置模板
 TemplateConfig templateConfig = TemplateGenerate();
 //自定義值
 InjectionConfig injectionConfig = FileGenerate();
 //配置包
 PackageConfig packageConfig = PackageGenerate();
 //生成代碼
 new AutoGenerator().setGlobalConfig(config)
  .setTemplate(templateConfig)//自定義模板路徑
  .setCfg(injectionConfig)
  .setDataSource(dataSourceConfig)
  .setStrategy(strategyConfig)
  .setPackageInfo(packageConfig)
  .execute();
 }
}

一定要註意!!!InjectionConfig方法中自定義的Map返回對象可以返回給模板調用,調用方法是${cfg.xxx}

vm模板代碼實例

package ${package.Controller}; //這樣寫是依據步驟2的PackageConfig方法配置

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import ${package.Entity}.${cfg.ClassName};
import ${package.Service}.${cfg.ClassName}Service;
import com.rent.model.AjaxResult;

/**
 * ${cfg.moduleName}Controller
 *
 * @author ${author}
 * @date ${cfg.datetime}
 */
@Controller
@RequestMapping("/${cfg.moduleName}/${cfg.className}")
public class ${cfg.ClassName}Controller extends BaseController

  @Autowired
  private ${cfg.ClassName}Service ${cfg.className}Service;

  /**
   * 查詢${cfg.className}列表
   */
  @GetMapping("/list")
  public TableDataInfo list(@RequestParam int pageNumber, @RequestParam int pageSize) {

 Page<${cfg.ClassName}> page = ${cfg.className}Service.select${cfg.ClassName}Page(pageNumber, pageSize);
 return page;
  }

  /**
   * 新增保存${cfg.ClassName}
   */
  @PostMapping("/add${cfg.ClassName}")
  public AjaxResult addSave(${cfg.ClassName} ${cfg.ClassName}) {

 boolean ret = ${cfg.ClassName}Service.save(${cfg.ClassName});
 return new AjaxResult(ret, ret ? "成功" : "失敗");
  }

  /**
   * 修改保存${cfg.ClassName}
   */
  @PostMapping("/edit")
  public AjaxResult editSave(${cfg.ClassName} ${cfg.ClassName}) {

 boolean ret = ${cfg.ClassName}Service.updateById(${cfg.ClassName});
 return new AjaxResult(ret, ret ? "成功" : "失敗");
  }

 @PostMapping("deleteById")
 @ApiOperation("根據ID刪除${cfg.ClassName}")
 public AjaxResult<${cfg.ClassName}> deleteById(Long id) {
 boolean ret = ${cfg.ClassName}Service.removeById(id);
 return new AjaxResult(true, ret ? "成功" : "失敗");
 }

 @PostMapping("findById")
 @ApiOperation("根據ID查詢${cfg.ClassName}")
 public AjaxResult<${cfg.ClassName}> findById(Long id) {
 ${cfg.ClassName} user = ${cfg.ClassName}Service.getById(id);
 return new AjaxResult(true, "成功", user);
 }
}

最後如果需要更詳細的vm調用請參閱官方文檔:https://baomidou.com/config/generator-config.html#datasource

到此這篇關於詳解使用Mybatis-plus + velocity模板生成自定義的代碼的文章就介紹到這瞭,更多相關Mybatis-plus velocity生成自定義代碼內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: