欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-23 18:52:35
pom.xml文件的配置 com.baomidou mybat...

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调用请参阅官方文档:

到此这篇关于详解使用mybatis-plus + velocity模板生成自定义的代码的文章就介绍到这了,更多相关mybatis-plus velocity生成自定义代码内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!