使用Mybatis-plus + velocity模板生成自定义的代码

缑修齐
2023-12-01
  1. 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>
  1. 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}

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

 类似资料: