• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Mybatis Plus代码生成器(时间管理大师)

mybatis 搞代码 4年前 (2022-01-09) 38次浏览 已收录 0个评论

1. 前言

对于写Crud的老司机来说时间非常宝贵,一些样板代码写不但费时费力,而且枯燥无味。经常有小伙伴问我,胖哥你怎么天天那么有时间去搞新东西,透露一下秘诀呗。

好吧,今天就把Mybatis-plus的代码生成器分享出来,让你也成为一个优秀的时间管理大师。

2. 基本依赖

以Spring Boot和MySQL为例,你需要下面这些依赖:

<!-- lombok 如果不使用 需要修改代码生成器的相关配置 -->
<dependency>
 <groupId>org.projectlombok</groupId>
 <artifactId>lombok</artifactId>
 <scope>compile</scope>
</dependency>
<!-- 连接池 你可以使用其它替换掉 -->
<dependency>
 <groupId>com.zaxxer</groupId>
 <artifactId>HikariCP</artifactId>
</dependency>
<!-- mysql -->
<dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis plus starter -->
<dependency>
 <groupId>com.baomidou</groupId>
 <artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<!-- mybatis plus 生成器模块 -->
<dependency>
 <groupId>com.baomidou</groupId>
 <artifactId>mybatis-plus-generator</artifactId>
 <scope>compile</scope>
 <optional>true</optional>
</dependency>
<!-- 引入freemarker包 作为代码生成器引擎 -->
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-freemarker</artifactId>
 <scope>compile</scope>
 <optional>true</optional>
</dependency>

然后配置好你的数据库,确保数据库连接通讯畅通。

3. 定制代码生成器

这里我期望生成的目录结构是这样的:

于是我花了点时间定制了一些生成器的配置,代码如下,就是这么硬核!

package cn.felord.mybatis.util;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.eng<div>本文来源gaodai^.ma#com搞#代!码网</div>ine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


/**
 * 代码生成器配置
 *
 * @author felord
 * @since 10 :39 2018/9/9
 */
public class CodeGenerator {
 private String dbUrl;
 private String userName;
 private String password;
 private String dir;
 private String xmlDir;
 private String packageName;

 private CodeGenerator() {
 }

 /**
 * The type Config builder.
 */
 public static class ConfigBuilder {

 private String dbUrl;
 private String userName;
 private String password;
 private String dir;
 private String xmlDir;
 private String packageName;


 /**
  * Db url config builder.
  *
  * @param dbUrl the db url
  * @return the config builder
  */
 public ConfigBuilder dbUrl(final String dbUrl) {
  this.dbUrl = dbUrl;
  return this;
 }

 /**
  * User name config builder.
  *
  * @param userName the user name
  * @return the config builder
  */
 public ConfigBuilder userName(final String userName) {
  this.userName = userName;
  return this;
 }

 /**
  * Password config builder.
  *
  * @param password the password
  * @return the config builder
  */
 public ConfigBuilder password(final String password) {
  this.password = password;
  return this;
 }

 /**
  * Dir config builder.
  *
  * @param dir the dir
  * @return the config builder
  */
 public ConfigBuilder dir(final String dir) {
  this.dir = dir;
  return this;
 }

 /**
  * Dir config builder.
  *
  * @param xmlDir the dir
  * @return the config builder
  */
 public ConfigBuilder xmlDir(final String xmlDir) {
  this.xmlDir = xmlDir;
  return this;
 }

 /**
  * Package name config builder.
  *
  * @param packageName the package name
  * @return the config builder
  */
 public ConfigBuilder packageName(final String packageName) {
  this.packageName = packageName;
  return this;
 }

 /**
  * Build code generator.
  *
  * @return the code generator
  */
 public CodeGenerator build() {
  CodeGenerator generator = new CodeGenerator();

  generator.dbUrl = Optional.of(this.dbUrl).get();
  generator.userName = Optional.of(this.userName).get();
  generator.password = Optional.of(this.password).get();
  generator.dir = Optional.of(this.dir).get();
  generator.xmlDir = Optional.of(this.xmlDir).get();
  generator.packageName = Optional.of(this.packageName).get();
  return generator;
 }
 }


 /**
 * Code.
 *
 * @param tableNames the table names
 */
 public void code(String... tableNames) {
 codingMysql(true, false, true, this.dbUrl, this.userName, this.password, this.dir, this.xmlDir, this.packageName, tableNames);
 }

 /**
 *
 * 生成器核心部分
 *
 * @param serviceNameStartWithI 是否前缀I
 * @param createController 是否生成controller
 * @param useLombok  是否使用 lombok
 * @param dbUrl   数据库连接
 * @param username  用户名称
 * @param password  密码
 * @param outDir  输出目录
 * @param xmlDir  xml 文件目录
 * @param packageName  包路径
 * @param tableNames  表名称
 */
 private static void codingMysql(boolean serviceNameStartWithI,
     boolean createController,
     boolean useLombok,
     String dbUrl,
     String username,
     String password,
     String outDir,
     String xmlDir,
     String packageName,
     String... tableNames) {
 GlobalConfig config = new GlobalConfig();
 DataSourceConfig dataSourceConfig = new DataSourceConfig();
// 数据库类型 这里使用 mysql
 dataSourceConfig.setDbType(DbType.MYSQL)
  .setUrl(dbUrl)
  .setUsername(username)
  .setPassword(password)
//  驱动名称 这里使用mysql
  .setDriverName("com.mysql.jdbc.Driver");

 // 自定义xml输出路径
 InjectionConfig cfg = new InjectionConfig() {
  @Override
  public void initMap() {
  // to do nothing
  }
 };
 List<FileOutConfig> focList = new ArrayList<>();
// 你也可以定制 xml 的模板
 focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
  @Override
  public String outputFile(TableInfo tableInfo) {
  // 自定义xml文件的路径
  return xmlDir + "/mapper/" + tableInfo.getMapperName() + StringPool.DOT_XML;
  }
 });
 cfg.setFileOutConfigList(focList);


// 策略配置项
 StrategyConfig strategyConfig = new StrategyConfig();
 strategyConfig
  .setCapitalMode(false)
//  是否使用 lombok
  .setEntityLombokModel(useLombok)
//  下划线转驼峰
  .setNaming(NamingStrategy.underline_to_camel)
  //修改替换成你需要的表名,多个表名传数组
  .setInclude(tableNames);
// 使用 AR 模式
 config.setActiveRecord(true)
//  设置头注释的 author
  .setAuthor("system")
//  项目输出路径
  .setOutputDir(outDir)
//  是否覆盖已经生成的同名文件
  .setFileOverride(true)
//  雪花算法生成id
  .setIdType(IdType.ASSIGN_ID)
//  是否使用缓存
  .setEnableCache(false)
//  是否生成 xml 中的 基础 resultMap
  .setBaseResultMap(true);
 if (!serviceNameStartWithI) {
//  Service 层的 通用格式后缀
  config.setServiceName("%sService");
 }
//  实体类包名
 PackageConfig packageConfig = new PackageConfig().setParent(packageName).setEntity("entity");
 TemplateConfig templateConfig = new TemplateConfig().setXml(null);
// 这里选择不生成 controller 实际上 生成的大多不符合我们需要 到服务层就行了
 if (!createController) {
  templateConfig.setController(null);
 }
// 整合起来运行
 new AutoGenerator()
  .setGlobalConfig(config)
  .setTemplateEngine(new FreemarkerTemplateEngine())
  .setDataSource(dataSourceConfig)
  .setStrategy(strategyConfig)
  .setPackageInfo(packageConfig)
  .setCfg(cfg)
  .setTemplate(templateConfig)
  .execute();
 }

}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Mybatis Plus代码生成器(时间管理大师)

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址