Mybatis-Plus自動生成代碼的實(shí)現(xiàn)示例
1、簡介
MyBatis-Plus (opens new window)(簡稱 MP)是一個 MyBatis (opens new window)的增強(qiáng)工具,在 MyBatis 的基礎(chǔ)上只做增強(qiáng)不做改變,為簡化開發(fā)、提高效率而生
特性
- 無侵入:只做增強(qiáng)不做改變,引入它不會對現(xiàn)有工程產(chǎn)生影響,如絲般順滑
- 損耗?。簡蛹磿詣幼⑷牖?CURD,性能基本無損耗,直接面向?qū)ο蟛僮?/li>
- 強(qiáng)大的 CRUD 操作:內(nèi)置通用 Mapper、通用 Service,僅僅通過少量配置即可實(shí)現(xiàn)單表大部分 CRUD 操作,更有強(qiáng)大的條件構(gòu)造器,滿足各類使用需求
- 支持 Lambda 形式調(diào)用:通過 Lambda 表達(dá)式,方便的編寫各類查詢條件,無需再擔(dān)心字段寫錯
- 支持主鍵自動生成:支持多達(dá) 4 種主鍵策略(內(nèi)含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解決主鍵問題
- 支持 ActiveRecord 模式:支持 ActiveRecord 形式調(diào)用,實(shí)體類只需繼承 Model 類即可進(jìn)行強(qiáng)大的 CRUD 操作
- 支持自定義全局通用操作:支持全局通用方法注入( Write once, use anywhere )
- 內(nèi)置代碼生成器:采用代碼或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 層代碼,支持模板引擎,更有超多自定義配置等您來使用
- 內(nèi)置分頁插件:基于 MyBatis 物理分頁,開發(fā)者無需關(guān)心具體操作,配置好插件之后,寫分頁等同于普通 List 查詢
- 分頁插件支持多種數(shù)據(jù)庫:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多種數(shù)據(jù)庫
- 內(nèi)置性能分析插件:可輸出 SQL 語句以及其執(zhí)行時間,建議開發(fā)測試時啟用該功能,能快速揪出慢查詢
- 內(nèi)置全局?jǐn)r截插件:提供全表 delete 、 update 操作智能分析阻斷,也可自定義攔截規(guī)則,預(yù)防誤操作
支持?jǐn)?shù)據(jù)庫
任何能使用 MyBatis 進(jìn)行 CRUD, 并且支持標(biāo)準(zhǔn) SQL 的數(shù)據(jù)庫,具體支持情況如下,如果不在下列表查看分頁部分教程 PR 您的支持。
MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss
,ClickHouse,Sybase,OceanBase,F(xiàn)irebird,Cubrid,Goldilocks,csiidb,informix,TDengine,redshift
達(dá)夢數(shù)據(jù)庫,虛谷數(shù)據(jù)庫,人大金倉數(shù)據(jù)庫,南大通用(華庫)數(shù)據(jù)庫,南大通用數(shù)據(jù)庫,神通數(shù)據(jù)庫,瀚高數(shù)據(jù)庫,優(yōu)炫數(shù)據(jù)庫
2、代碼生成器
AutoGenerator 是 MyBatis-Plus 的代碼生成器,通過 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各個模塊的代碼,極大的提升了開發(fā)效率。
/** * <p> * mysql 代碼生成器 * </p> */ public class CodeGenerator { /** * 運(yùn)行啟動 */ public static void main(String[] args) { //獲取控制臺的數(shù)據(jù) Scanner scanner = new Scanner(System.in); // 代碼生成器 AutoGenerator mpg = new AutoGenerator(); //~~~~~~~~~~~~~~~~~~~~~全局配置~~~~~~~~~~開始~~~~~~~~~ GlobalConfig gc = new GlobalConfig(); //System.out.println("請輸入文件輸出目錄的模塊或者項(xiàng)目的地址:"); //String projectPath = scanner.nextLine(); String projectPath = System.getProperty("user.dir"); //工程根目錄 System.out.println(projectPath); gc.setOutputDir(projectPath + "/src/main/java"); //生成文件的輸出目錄 gc.setAuthor("tigerhhzz"); //作者 gc.setFileOverride(true); //是否覆蓋已有文件 默認(rèn)值:false gc.setOpen(false); //是否打開輸出目錄 默認(rèn)值:true gc.setBaseColumnList(true); //開啟 baseColumnList 默認(rèn)false gc.setBaseResultMap(true); //開啟 BaseResultMap 默認(rèn)false //gc.setEntityName("%sEntity"); //實(shí)體命名方式 默認(rèn)值:null 例如:%sEntity 生成 UserEntity gc.setMapperName("%sMapper"); //mapper 命名方式 默認(rèn)值:null 例如:%sDao 生成 UserDao gc.setXmlName("%sMapper"); //Mapper xml 命名方式 默認(rèn)值:null 例如:%sDao 生成 UserDao.xml gc.setServiceName("%sService"); //service 命名方式 默認(rèn)值:null 例如:%sBusiness 生成 UserBusiness gc.setServiceImplName("%sServiceImpl"); //service impl 命名方式 默認(rèn)值:null 例如:%sBusinessImpl 生成 UserBusinessImpl gc.setControllerName("%sController"); //controller 命名方式 默認(rèn)值:null 例如:%sAction 生成 UserAction mpg.setGlobalConfig(gc); //~~~~~~~~~~~~~~~~~~~~~全局配置~~~~~~~~~~結(jié)束~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~數(shù)據(jù)源配置~~~~~~~~~~開始~~~~~~~~~ DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/tigervueblog?useUnicode=true&useSSL=false&characterEncoding=utf8"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123456"); mpg.setDataSource(dsc); //~~~~~~~~~~~~~~~~~~~~~數(shù)據(jù)源配置~~~~~~~~~~結(jié)束~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~包配置~~~~~~~~~~開始~~~~~~~~~ PackageConfig pc = new PackageConfig(); // pc.setModuleName(scanner("模塊名")); // pc.setParent("com.stu"); System.out.println("請輸入模塊名:"); String name = scanner.nextLine(); //自定義包配置 pc.setParent(name); pc.setModuleName(null); pc.setMapper("mapper"); pc.setEntity("domain"); pc.setService("service"); pc.setServiceImpl("service.impl"); pc.setController("controller"); mpg.setPackageInfo(pc); //~~~~~~~~~~~~~~~~~~~~~包配置~~~~~~~~~~結(jié)束~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~自定義配置~~~~~~~~~~開始~~~~~~~~~ InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; List<FileOutConfig> focList = new ArrayList<>(); focList.add(new FileOutConfig("/templates/mapper.xml.ftl") { @Override public String outputFile(TableInfo tableInfo) { // 自定義輸入文件名稱 return projectPath + "/src/main/resources/mapper/" + /*pc.getModuleName() + "/" +*/ tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); //~~~~~~~~~~~~~~~~~~~~~自定義配置~~~~~~~~~~結(jié)束~~~~~~~~~ //這里不自動生成xml,改為自定義生成 mpg.setTemplate(new TemplateConfig().setXml(null)); //~~~~~~~~~~~~~~~~~~~~~策略配置~~~~~~~~~~開始~~~~~~~~~ // 策略配置 數(shù)據(jù)庫表配置,通過該配置,可指定需要生成哪些表或者排除哪些表 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); //表名生成策略 strategy.setColumnNaming(NamingStrategy.underline_to_camel);//數(shù)據(jù)庫表字段映射到實(shí)體的命名策略, 未指定按照 naming 執(zhí)行 // strategy.setCapitalMode(true); // 全局大寫命名 ORACLE 注意 // strategy.setTablePrefix("prefix"); //表前綴 // strategy.setSuperEntityClass("com.stu.domain"); //自定義繼承的Entity類全稱,帶包名 // strategy.setSuperEntityColumns(new String[] { "test_id", "age" }); //自定義實(shí)體,公共字段 strategy.setEntityLombokModel(true); //【實(shí)體】是否為lombok模型(默認(rèn) false strategy.setRestControllerStyle(true); //生成 @RestController 控制器 // strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController"); //自定義繼承的Controller類全稱,帶包名 // strategy.setInclude(scanner("表名")); //需要包含的表名,允許正則表達(dá)式(與exclude二選一配置) System.out.println("請輸入映射的表名(多個表名英文逗號分割):"); String tables = scanner.nextLine(); String[] num = tables.split(","); strategy.setInclude(num); // 需要生成的表可以多張表 // strategy.setExclude(new String[]{"test"}); // 排除生成的表 //如果數(shù)據(jù)庫有前綴,生成文件時是否要前綴acl_ // strategy.setTablePrefix("bus_"); // strategy.setTablePrefix("sys_"); strategy.setControllerMappingHyphenStyle(true); //駝峰轉(zhuǎn)連字符 strategy.setTablePrefix(pc.getModuleName() + "_"); //是否生成實(shí)體時,生成字段注解 mpg.setStrategy(strategy); //~~~~~~~~~~~~~~~~~~~~~策略配置~~~~~~~~~~結(jié)束~~~~~~~~~ //模板引擎配置,使用Freemarker,默認(rèn) Velocity 可選模板引擎 Beetl\ mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }
3、詳細(xì)使用教程
3.1 兩個mysql數(shù)據(jù)庫:
m_user腳本:
CREATE TABLE `m_user` ( `id` bigint NOT NULL AUTO_INCREMENT COMMENT '自動遞增id', `username` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用戶名', `avatar` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用戶頭像', `email` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '郵箱地址', `password` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '密碼', `status` int NOT NULL DEFAULT '0' COMMENT '0代表正常,-1代表被鎖定', `created` datetime DEFAULT NULL COMMENT '注冊時間', `last_login` datetime DEFAULT NULL COMMENT '最后登錄時間', PRIMARY KEY (`id`), KEY `UK_USERNAME` (`username`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;
m_blog腳本:
CREATE TABLE `m_blog` ( `id` bigint NOT NULL AUTO_INCREMENT, `user_id` bigint NOT NULL, `title` varchar(255) NOT NULL, `description` varchar(255) NOT NULL, `content` longtext, `created` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP, `status` tinyint DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
3.2 創(chuàng)建springboot項(xiàng)目
3.3 添加依賴
MyBatis-Plus 從 3.0.3 之后移除了代碼生成器與模板引擎的默認(rèn)依賴,需要手動添加相關(guān)依賴:
項(xiàng)目完整pom文件:(注意版本號)
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.6</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.tigerhhzz</groupId> <artifactId>springboot-mybatisplus-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot-mybatisplus-demo</name> <description>Demo project for Spring Boot MP</description> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- 包含spirng Mvc ,tomcat的包包含requestMapping restController 等注解 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <!--mysql數(shù)據(jù)庫 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.28</version> </dependency> <!-- druid 連接池 --> <!-- <dependency>--> <!-- <groupId>com.alibaba</groupId>--> <!-- <artifactId>druid</artifactId>--> <!-- <version>1.2.8</version>--> <!-- </dependency>--> <!-- mybatis版本必須與druid版本兼容,否則無法創(chuàng)建DataSource --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.2.0</version> </dependency> <!-- 引入freemarker模板引擎供mp生成代碼--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <!--mp代碼生成器--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.3.0</version> </dependency> <!-- hutool工具類--> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.3.3</version> </dependency> <!-- lombok注解--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!-- 日志打印--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency> <!-- 單元測試--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project>
3.4 編輯application.yml文件
server: port: 8082 servlet: context-path: / spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver # test-mybatis url: jdbc:mysql://127.0.0.1:3306/tigervueblog?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true username: root password: 123456 jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8 serialization: write-dates-as-timestamps: false mybatis-plus: configuration: map-underscore-to-camel-case: true auto-mapping-behavior: full log-impl: org.apache.ibatis.logging.stdout.StdOutImpl mapper-locations: classpath*:mapper/**/*Mapper.xml global-config: # ?????????? db-config: # ???? logic-not-delete-value: 1 # ????? logic-delete-value: 0
3.5 主啟動類
package com.mpautocode; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author tigerhhzz * @date 2023/4/28 9:16 */ @Slf4j @SpringBootApplication public class springbootmptest { public static void main(String[] args) { SpringApplication.run(springbootmptest.class, args); log.info("springbootmptest啟動成功~~~~^…^~~~~^…^~~~~~^…^~~~~"); } }
4、運(yùn)行
4.1 項(xiàng)目最終結(jié)構(gòu)
4.2 運(yùn)行代碼生成器類
輸入模塊名:
請輸入映射的表名(多個表名英文逗號分割):
生成完成
4.3 測試運(yùn)行controller
在運(yùn)行主啟動類之前,檢查在生成好的mapper接口中加入@Mapper注解。
編寫一個usercontroller
package com.mpautocode.controller; import com.mpautocode.domain.MUser; import com.mpautocode.service.MUserService; import com.tigerhhzz.springbootmybatisplusdemo.entities.CommonResult; import com.tigerhhzz.springbootmybatisplusdemo.entities.User; import com.tigerhhzz.springbootmybatisplusdemo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * <p> * 前端控制器 * </p> * * @author tigerhhzz * @since 2023-04-28 */ @RestController @RequestMapping("/m-user") public class MUserController { @Autowired MUserService userService; /** * list(查詢所有) * @return */ @GetMapping("/list") public CommonResult list(){ // 查詢所有 List<MUser> list = userService.list(); return new CommonResult(200,"查詢數(shù)據(jù)成功",list); } }
運(yùn)行結(jié)果:
到此這篇關(guān)于Mybatis-Plus自動生成代碼的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)Mybatis-Plus自動生成代碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot中使用undertow踩坑記(最新推薦)
這篇文章主要介紹了springboot中使用undertow踩坑記,springboot內(nèi)置類web中間件,將web服務(wù)器管理權(quán)交給了容器,本文分步驟給大家介紹的非常詳細(xì),需要的朋友可以參考下2024-08-08springboot2.0整合logback日志的詳細(xì)代碼
這篇文章主要介紹了springboot2.0整合logback日志的應(yīng)用場景分析,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-02-02Java結(jié)構(gòu)型設(shè)計(jì)模式之適配器模式詳解
適配器模式,即將某個類的接口轉(zhuǎn)換成客戶端期望的另一個接口的表示,主要目的是實(shí)現(xiàn)兼容性,讓原本因?yàn)榻涌诓黄ヅ洌瑳]辦法一起工作的兩個類,可以協(xié)同工作。本文將通過示例詳細(xì)介紹適配器模式,需要的可以參考一下2022-09-09Maven在Windows中的配置以及IDE中的項(xiàng)目創(chuàng)建實(shí)例
下面小編就為大家?guī)硪黄狹aven在Windows中的配置以及IDE中的項(xiàng)目創(chuàng)建實(shí)例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09