Explanation of Generating Custom Code Using Mybatis plus + velocity Template

  • 2021-09-05 00:15:16
  • OfStack

Configuration of pom. xml file


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

<!--  Code generator template  -->
<dependency>
  <groupId>org.apache.velocity</groupId>
  <artifactId>velocity</artifactId>
  <version>1.7</version>
</dependency>

CodeGenerator Configuration File


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;

/**
 *  Code generator 
 */
@Log
public class CodeGenerator {

 // Item storage location 
 public static String PROJECT_GENERATE_DISK = "E:\\";
 // Package name 
 public static String PARENT_PACKAGE_NAME = "com";
 // Package name 
 public static String PACKAGE_NAME = "rent.security";
 // Database address 
 public static String DB_URL = "jdbc:mysql://localhost:3306/mp?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC";
 // Database instance name 
 public static String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
 // Database user 
 public static String USER = "root";
 // Database password 
 public static String PASSWORD = "root";
 // Database schema
 public static String SCHEMA = "mp";
 // The name of the table to query 
 public static String TABLE_NAMES = "sys_role_menu";
 // Founder 
 public static String AUTHOR = "jmm";
 // Whether to force annotations 
 public static boolean ENABLE_TABLE_FIELD_ANNOTATION = false;
 // The generated annotation is attached to the IdType Type 
 public static IdType TABLE_IDTYPE = null;
 // Generated Service  Whether the interface class name is based on I Beginning   The default is to I Beginning  user Table  -> IUserService, UserServiceImpl
 public static boolean SERVICE_CLASS_NAME_START_WITHI = false;

 /**
 *  Global configuration 
 */
 private static GlobalConfig GlobalGenerate() {
 GlobalConfig config = new GlobalConfig();
 config.setActiveRecord(false)//  No need ActiveRecord Property change to false
  .setIdType(TABLE_IDTYPE)
  .setEnableCache(false)// XML 2 Level cache 
  .setAuthor(AUTHOR)
  .setBaseResultMap(true)// XML ResultMap
  .setBaseColumnList(false)// XML columList
  .setOutputDir(PROJECT_GENERATE_DISK + "\\java" )
  .setFileOverride(true)
  .setControllerName("%sController" );// Custom file naming, note  %s  Table entity properties are automatically populated! 

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

 /**
 *  Data source configuration 
 */
 private static DataSourceConfig DaoSourceGenerate() {
 DataSourceConfig dataSourceConfig = new DataSourceConfig();
 DbType type = DbType.MYSQL;
 dataSourceConfig.setDbType(type)// Database type 
  .setUrl(DB_URL)// Database address 
  .setUsername(USER)// Database user name 
  .setPassword(PASSWORD)// Database password 
  .setDriverName(DRIVER_CLASS_NAME)// Instance name 
  .setSchemaName(SCHEMA);
 return dataSourceConfig;
 }

 /**
 *  Policy configuration 
 */
 private static StrategyConfig StrategyGenerate() {
 StrategyConfig strategyConfig = new StrategyConfig();
 strategyConfig.setVersionFieldName("version" )
  .setCapitalMode(true)//  Global uppercase naming  ORACLE  Attention 
  .setEntityLombokModel(false)
  .setNaming(NamingStrategy.underline_to_camel)//  Table name generation strategy 
  .entityTableFieldAnnotationEnable(ENABLE_TABLE_FIELD_ANNOTATION)
  .setInclude(TABLE_NAMES)// Modify and replace it with the table name you need, and transfer multiple table names to an array 
  .setEntityColumnConstant(true)//  Whether Entity generates field constants (default  false ) public static final String ID = "test_id";
  .setEntityBuilderModel(true);//  Whether Entity is a builder model (default  false ) public User setName(String name) {this.name = name; return this;}
 return strategyConfig;
 }

 /**
 *  Custom template configuration 
 */
 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";

 /**
 *  Custom files and key
 */
 private static InjectionConfig FileGenerate() {
 InjectionConfig injectionConfig = new InjectionConfig() {
  @Override
  public void initMap() {// Custom parameters 
  Map<String, Object> map = new HashMap<>();
  // These custom values are in the vm The syntax of the template is passed through the ${cfg.xxx} To call. 
  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;
 }

 /**
 *  Package configuration 
 */
 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) {
 // Global configuration 
 GlobalConfig config = GlobalGenerate();
 // Configure the data source 
 DataSourceConfig dataSourceConfig = DaoSourceGenerate();
 // Configuration policy 
 StrategyConfig strategyConfig = StrategyGenerate();
 // Configuration template 
 TemplateConfig templateConfig = TemplateGenerate();
 // Custom value 
 InjectionConfig injectionConfig = FileGenerate();
 // Configuration package 
 PackageConfig packageConfig = PackageGenerate();
 // Generate code 
 new AutoGenerator().setGlobalConfig(config)
  .setTemplate(templateConfig)// Custom template path 
  .setCfg(injectionConfig)
  .setDataSource(dataSourceConfig)
  .setStrategy(strategyConfig)
  .setPackageInfo(packageConfig)
  .execute();
 }
}

1 Be sure to pay attention! ! ! The custom Map return object in the InjectionConfig method can be returned to the template call with the call method of ${cfg. xxx}

vm Template Code Example


package ${package.Controller}; // This is written according to the steps 2 Adj. PackageConfig Method configuration 

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;

  /**
   *  Query ${cfg.className} List 
   */
  @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;
  }

  /**
   *  Add Save ${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 ? " Success " : " Failure ");
  }

  /**
   *  Modify and save ${cfg.ClassName}
   */
  @PostMapping("/edit")
  public AjaxResult editSave(${cfg.ClassName} ${cfg.ClassName}) {

 boolean ret = ${cfg.ClassName}Service.updateById(${cfg.ClassName});
 return new AjaxResult(ret, ret ? " Success " : " Failure ");
  }

 @PostMapping("deleteById")
 @ApiOperation(" According to ID Delete ${cfg.ClassName}")
 public AjaxResult<${cfg.ClassName}> deleteById(Long id) {
 boolean ret = ${cfg.ClassName}Service.removeById(id);
 return new AjaxResult(true, ret ? " Success " : " Failure ");
 }

 @PostMapping("findById")
 @ApiOperation(" According to ID Query ${cfg.ClassName}")
 public AjaxResult<${cfg.ClassName}> findById(Long id) {
 ${cfg.ClassName} user = ${cfg.ClassName}Service.getById(id);
 return new AjaxResult(true, " Success ", user);
 }
}

Finally, if you need more detailed vm calls, please refer to the official document: https://baomidou.com/config/generator-config.html # datasource


Related articles: