mybatisplus代碼生成器_想做時間管理大師?你可以試試Mybatis Plus代碼生成器

88d2c422a2bccb0b01f7e4f2d56f2453.png

1. 前言

對于寫Crud的老司機來說時間非常寶貴,一些樣板代碼寫不但費時費力,而且枯燥無味。經常有小伙伴問我,胖哥你怎么天天那么有時間去搞新東西,透露一下秘訣唄。

135b38efb604a948fdcbc3cb2e8c8d2f.png

好吧,今天就把Mybatis-plus的代碼生成器分享出來,讓你也成為一個優秀的時間管理大師。

2. 基本依賴

Spring BootMySQL為例,你需要下面這些依賴:

 ? ?org.projectlombok ? ?lombok ? ?compile ? ?com.zaxxer ? ?HikariCP ? ?mysql ? ?mysql-connector-java ? ?com.baomidou ? ?mybatis-plus-boot-starter ? ?com.baomidou ? ?mybatis-plus-generator ? ?compile ? ?true ? ?org.springframework.boot ? ?spring-boot-starter-freemarker ? ?compile ? ?true

然后配置好你的數據庫,確保數據庫連接通訊暢通。

3. 定制代碼生成器

這里我期望生成的目錄結構是這樣的:

23b633eb965cf32eab8ba2f2a48ba33a.png

于是我花了點時間定制了一些生成器的配置,代碼如下,就是這么硬核!

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.engine.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 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(); ?  }?}?

如果我生成的目錄結構能夠滿足你的需要,那就巧了,直接拿去用;如果不滿足需要,你可以按照注釋的說明進行微調。18年搞的用了好幾年,沒出過什么亂子。

4. 代碼生成器的使用

使用起來非常簡單,確保數據庫能夠使用JDBC連接成功,寫個main方法,配置一下,跑起來就是了:

/** * @author felord.cn * @since 11:34 **/public class AutoCoding { ? ?public static void main(String[] args) {?// ? ? ? ?  maven 工程 main 包的全路徑 ? ? ? ?final String mainDir = "C:IdeaProjectsbc-recylingsrcmain";? ? ? ? ?CodeGenerator.ConfigBuilder builder = new CodeGenerator.ConfigBuilder();? ? ? ? ?CodeGenerator codeGenerator = builder// ? ? ? ? ? ? ?  數據庫連接 ? ? ? ? ? ? ?  .dbUrl("jdbc:mysql://localhost:3306/test")// ? ? ? ? ? ? ?  賬戶 ? ? ? ? ? ? ?  .userName("root")// ? ? ? ? ? ? ?  密碼 ? ? ? ? ? ? ?  .password("123456") ? ? ? ? ? ? ? ?// 生成類位置 ? ? ? ? ? ? ?  .dir(mainDir + "java") ? ? ? ? ? ? ? ?// 生成xml 位置 ? ? ? ? ? ? ?  .xmlDir(mainDir + "resources") ? ? ? ? ? ? ? ?// 包引用路徑 ? ? ? ? ? ? ?  .packageName("cn.felord.mybatis") ? ? ? ? ? ? ?  .build();? ? ? ? ?//根據表生成后臺代碼 ? ? ? ?codeGenerator.code("user_info");?? ?  }}

然后代碼就生成了,是不是非常的好用?恭喜你獲得了 時間管理大師 榮譽稱號。

切記不要炫耀,否則需求加倍。

5. 總結

雖然好用,但是建議新手不要使用,多手寫一下代碼。另外復雜的SQL還是建議自己寫,多鍛煉寫SQL的能力。如果你在使用中有什么問題,可以私信我進行溝通。如果你有更加好用的可以通過留言分享給廣大條友。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/542565.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/542565.shtml
英文地址,請注明出處:http://en.pswp.cn/news/542565.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

安裝Oracle 11g RAC R2 之Linux DNS 配置

Oracle 11g RAC 集群中引入了SCAN(Single Client Access Name)的概念&#xff0c;也就是指集群的單客戶端訪問名稱。SCAN 這個特性為客戶端提供了單一的主機名&#xff0c;用于訪問集群中運行的 Oracle 數據庫。如果您在集群中添加或刪除節點&#xff0c;使用 SCAN 的客戶端無需…

c++ websocket客戶端_websocket使用

websocket使用一、介紹在項目開發過程中&#xff0c;很多時候&#xff0c;我們不可避免的需要實現的一個功能&#xff1a; 服務端實時發送信息給客戶端。比如實時公告、實時訂單通知、實時報警推送等等&#xff0c;登錄后的客戶端需要知道與它相關的實時信息&#xff0c;以便進…

漢子編碼比字母編碼長_字母/博客作者編碼問題(使用動態編程)

漢子編碼比字母編碼長Problem statement: 問題陳述&#xff1a; Shivang is a blog writer and he is working on two websites simultaneously. He has to write two types of blogs which are: Shivang是一位博客作家&#xff0c;他同時在兩個網站上工作。 他必須寫兩種類型…

php parent報錯,mac brew 安裝php擴展報錯:parent directory is world writable but not sticky

$ brew install php70-mcrypt報錯&#xff1a;Error: parent directory is world writable but not sticky搜索到github的答案https://github.com/Homebrew/legacy-homebrew/issues/40345原因&#xff1a;/tmp目錄權限不對$ ls -ld /private/tmp打印出來 /private/tmp 被標黃了…

在cordova中使用HTML5的多文件上傳

2019獨角獸企業重金招聘Python工程師標準>>> 我們先看看linkface給開放的接口&#xff1a; 字段類型必需描述api_idstring是API 賬戶api_secretstring是API 密鑰selfie_filefile見下方注釋需上傳的圖片文件 1&#xff0c;上傳本地圖片進行檢測時選取此參數selfie_ur…

python dataframe切片_python pandas dataframe 行列選擇,切片操作方法

SQL中的select是根據列的名稱來選取&#xff1b;Pandas則更為靈活&#xff0c;不但可根據列名稱選取&#xff0c;還可以根據列所在的position&#xff08;數字&#xff0c;在第幾行第幾列&#xff0c;注意pandas行列的position是從0開始&#xff09;選取。相關函數如下&#xf…

php根據設備判斷訪問,PHP判斷設備訪問來源

/*** 判斷用戶請求設備是否是移動設備* return bool*/function isMobile() {//如果有HTTP_X_WAP_PROFILE則一定是移動設備if (isset($_SERVER[HTTP_X_WAP_PROFILE])) {return true;}//如果via信息含有wap則一定是移動設備,部分服務商會屏蔽該信息if (isset($_SERVER[HTTP_VIA])…

機器學習 深度學習 ai_如何學習機器學習和人工智能?

機器學習 深度學習 aiSTRATEGY 戰略 Learn theory practical aspects. 學習理論和實踐方面的知識。 (At first get an overview of what you are going to learn). (首先獲得要學習的內容的概述)。 Gain a good hold/insight on each concept. 掌握/理解每個概念。 If you …

linux常用命令和配置

2019獨角獸企業重金招聘Python工程師標準>>> 啟動php&#xff1a; /etc/init.d/php-fpm restart 查看PHP運行目錄&#xff1a; which php /usr/bin/php 查看php-fpm進程數&#xff1a; ps aux | grep -c php-fpm 查看運行內存 /usr/bin/php -i|grep mem iptables如…

centos7時間同步_centos 8.x系統配置chrony時間同步服務

centos 8.x系統配置chrony時間同步服務CentOS 7.x默認使用的時間同步服務為ntp服務&#xff0c;但是CentOS 8開始在官方的倉庫中移除了ntp軟件&#xff0c;換成默認的chrony進行時間同步的服務&#xff0c;chrony既可以作為客戶端向其他時間服務器發送時間同步請求&#xff0c;…

php可以用scanf,C/C++中 使用scanf和printf如何讀入輸出double型數據。

黃舟2017-04-17 13:47:232樓注意scanf函數和printf函數是不同尋常的函數&#xff0c;因為它們都沒有將函數的參數限制為固定數量。scanf函數和printf函數又可變長度的參數列表。當調用帶可變長度參數列表的函數時&#xff0c;編譯器會安排float參數自動轉換成為double類型&…

ICWAI和ICWA的完整形式是什么?

ICWAI / ICWA&#xff1a;印度成本與工程會計師協會/印度兒童福利法 (ICWAI / ICWA: Institute of Cost and Works Accountants of India / Indian Child Welfare Act) 1)ICWAI&#xff1a;印度成本與工程會計師協會 (1) ICWAI: Institute of Cost and Works Accountants of In…

深入研究java.lang.Runtime類【轉】

轉自&#xff1a;http://blog.csdn.net/lastsweetop/article/details/3961911 目錄(?)[-] javalang 類 RuntimegetRuntimeexitaddShutdownHookremoveShutdownHookhaltrunFinalizersOnExitexecexecexecexecexecexecavailableProcessorsfreeMemorytotalMemorymaxMemorygcrunFina…

java隊列實現限流,java中應對高并發的兩種策略

目的&#xff1a;提高可用性通過ExecutorService實現隊列泄洪//含有20個線程的線程池private ExecutorService executorService Executors.newFixedThreadPool(20);將有并發壓力的下游代碼放入到線程池的submit方法中&#xff0c;如下&#xff1a;//同步調用線程池的submit方法…

crontab 日志_liunx 中定時清理過期日志文件

問題描述經常遇到日志文件過多&#xff0c;占用大量磁盤空間&#xff0c;需要定期刪除過期日志。問題涉及方面刪除過期日志的腳本。定時任務刪除任務腳本先查詢到過期的日志文件&#xff0c;然后刪除。語法find path -option [ -print ] [ -exec -ok command ] …

JavaScript | 數組的常用屬性和方法

JavaScript的通用屬性和數組方法 (Common properties and methods of array in JavaScript ) Properties/MethodsDescriptionsarray.lengthReturns the length of the array/total number of elements of the array array[index]Returns the item name stored at “index” pos…

php dbutils 使用,dbutilsapi

相對lisp?而?言,可以使?用.net的強?大api,實現各種酷炫功能。相對c#及arx?...文件utils.py的模塊名分別是mycompany.utils和 mycompany.web.utils。 mycompany......CouchDB -b 關閉后臺運行的 CouchDB : CouchDB -d web 訪問:http://127.0.0.1:5984/_utils/index.html E-…

html 導航欄

<!DOCTYPE html> <html> <head> <meta charset"utf-8"> <title>lvnian學習(http://lvnian.blog.51cto.com/)</title> <style> ul {list-style-type:none;margin:0;padding:0; }a:link,a:visited{display:block;font-weigh…

將搜索二叉樹轉換為鏈表_將給定的二叉樹轉換為雙鏈表(DLL)

將搜索二叉樹轉換為鏈表Given a Binary tree and we have to convert it to a Doubly Linked List (DLL). 給定二叉樹&#xff0c;我們必須將其轉換為雙鏈表(DLL)。 Algorithm: 算法&#xff1a; To solve the problem we can follow this algorithm: 為了解決這個問題&#…

cuda編程_CUDA刷新器:CUDA編程模型

CUDA刷新器&#xff1a;CUDA編程模型 CUDA Refresher: The CUDA Programming Model CUDA&#xff0c;CUDA刷新器&#xff0c;并行編程 這是CUDA更新系列的第四篇文章&#xff0c;它的目標是刷新CUDA中的關鍵概念、工具和初級或中級開發人員的優化。 CUDA編程模型提供了GPU體系結…