Mybatis-Plus實現(xiàn)自動生成代碼的操作步驟
前言
AutoGenerator 是 MyBatis-Plus 的代碼生成器,通過 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各個模塊的代碼,極大的提升了開發(fā)效率。
Our-task介紹
本篇博客是我的github上項目our-task:一個完整的清單管理系統(tǒng)的配套教程文檔,大家感興趣的話,可以去看看
操作步驟
創(chuàng)建SpringBoot項目
先在IDEA中創(chuàng)建一個SpringBoot的項目,一直next就可以創(chuàng)建完成

設(shè)置pom依賴
? <dependencies> ? ? ? <!-- ? ? ? SpringBoot通用依賴模塊--> ? ? ? <dependency> ? ? ? ? ? <groupId>org.springframework.boot</groupId> ? ? ? ? ? <artifactId>spring-boot-starter-web</artifactId> ? ? ? </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> ? ? ? <dependency> ? ? ? ? ? <groupId>org.springframework.boot</groupId> ? ? ? ? ? <artifactId>spring-boot-starter-test</artifactId> ? ? ? ? ? <scope>test</scope> ? ? ? </dependency> ? ? ? <!-- ? ? ? Mysql數(shù)據(jù)庫驅(qū)動--> ? ? ? <dependency> ? ? ? ? ? <groupId>mysql</groupId> ? ? ? ? ? <artifactId>mysql-connector-java</artifactId> ? ? ? ? ? <scope>runtime</scope> ? ? ? </dependency> ? ? ? <!--mp--> ? ? ? <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> ? </dependencies>
創(chuàng)建CodeGenerator類
這是mybatis-plus自動生成代碼的文件,我是把這個文件和DemoApplication放在同一級目錄下,大家把下面的代碼粘貼過去,需要設(shè)置數(shù)據(jù)庫的連接信息、service,controller、xml文件等代碼的自動生成目錄。
只要修改以下這些代碼位置就可以了
//這個路徑是生成路徑 gc.setOutputDir(projectPath + "/src/main/java");
// 數(shù)據(jù)源配置(這里替換為自己的數(shù)據(jù)庫配置)
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/our-task?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("abc+!@#123");
//這里配置生成的service/controller等代碼,放在哪個包下面
pc.setParent("com.example.demo");
// 配置生成的xml存放的位置 , 如果你 Entity 設(shè)置了前后綴、此處注意 xml 的名稱會跟著發(fā)生變化!! return projectPath + "/src/main/resources/mapper/" ? ? ? + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
第一次更改,可能會發(fā)現(xiàn)生成代碼的路徑和自己預(yù)想的不一樣,大家可以直接把生成的代碼刪掉,修改路徑,重新生成,多試試就行了
下面給大家貼出生成的全部代碼
package com.example.demo;
?
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
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.Scanner;
?
/**
* @program: our-task-study
* @description: mybatis-plus代碼自動生成類
* @author: water76016
* @create: 2020-09-24 16:45
**/
public class CodeGenerator {
? /**
? ? * 讀取控制臺內(nèi)容
? ? */
? public static String scanner(String tip) {
? ? ? Scanner scanner = new Scanner(System.in);
? ? ? StringBuilder help = new StringBuilder();
? ? ? help.append("請輸入" + tip + ":");
? ? ? System.out.println(help.toString());
? ? ? if (scanner.hasNext()) {
? ? ? ? ? String ipt = scanner.next();
? ? ? ? ? if (StrUtil.isEmpty(ipt) == false){
? ? ? ? ? ? ? return ipt;
? ? ? ? ? }
? ? ? }
? ? ? throw new MybatisPlusException("請輸入正確的" + tip + "!");
? }
?
? public static void main(String[] args) {
? ? ? // 代碼生成器
? ? ? AutoGenerator mpg = new AutoGenerator();
?
? ? ? // 全局配置
? ? ? GlobalConfig gc = new GlobalConfig();
? ? ? String projectPath = System.getProperty("user.dir");
? ? ? //這個路徑是生成路徑
? ? ? gc.setOutputDir(projectPath + "/src/main/java");
? ? ? gc.setAuthor("github:water76016");
? ? ? gc.setOpen(false);
? ? ? // gc.setSwagger2(true); 實體屬性 Swagger2 注解
? ? ? gc.setServiceName("%sService");
? ? ? mpg.setGlobalConfig(gc);
?
? ? ? // 數(shù)據(jù)源配置(這里替換為自己的數(shù)據(jù)庫配置)
? ? ? DataSourceConfig dsc = new DataSourceConfig();
? ? ? dsc.setUrl("jdbc:mysql://localhost:3306/our-task?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
? ? ? dsc.setDriverName("com.mysql.cj.jdbc.Driver");
? ? ? dsc.setUsername("root");
? ? ? dsc.setPassword("abc+!@#123");
? ? ? mpg.setDataSource(dsc);
?
? ? ? // 包配置
? ? ? PackageConfig pc = new PackageConfig();
? ? ? pc.setModuleName(null);
? ? ? //這里配置生成的service/controller等代碼,放在哪個包下面
? ? ? pc.setParent("com.example.demo");
? ? ? mpg.setPackageInfo(pc);
?
? ? ? // 自定義配置
? ? ? InjectionConfig cfg = new InjectionConfig() {
? ? ? ? ? @Override
? ? ? ? ? public void initMap() {
? ? ? ? ? ? ? // to do nothing
? ? ? ? ? }
? ? ? };
?
? ? ? // 如果模板引擎是 freemarker
? ? ? String templatePath = "/templates/mapper.xml.ftl";
? ? ? // 如果模板引擎是 velocity
? ? ? // String templatePath = "/templates/mapper.xml.vm";
?
? ? ? // 自定義輸出配置
? ? ? List<FileOutConfig> focList = new ArrayList<>();
? ? ? // 自定義配置會被優(yōu)先輸出
? ? ? focList.add(new FileOutConfig(templatePath) {
? ? ? ? ? @Override
? ? ? ? ? public String outputFile(TableInfo tableInfo) {
? ? ? ? ? ? ? // 配置生成的xml存放的位置 , 如果你 Entity 設(shè)置了前后綴、此處注意 xml 的名稱會跟著發(fā)生變化?。?
? ? ? ? ? ? ? return projectPath + "/src/main/resources/mapper/"
? ? ? ? ? ? ? ? ? ? ? + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
? ? ? ? ? }
? ? ? });
?
? ? ? cfg.setFileOutConfigList(focList);
? ? ? mpg.setCfg(cfg);
?
? ? ? // 配置模板
? ? ? TemplateConfig templateConfig = new TemplateConfig();
?
? ? ? templateConfig.setXml(null);
? ? ? mpg.setTemplate(templateConfig);
?
? ? ? // 策略配置
? ? ? StrategyConfig strategy = new StrategyConfig();
? ? ? strategy.setNaming(NamingStrategy.underline_to_camel);
? ? ? strategy.setColumnNaming(NamingStrategy.underline_to_camel);
? ? ? strategy.setEntityLombokModel(true);
? ? ? strategy.setRestControllerStyle(true);
? ? ? strategy.setInclude(scanner("表名,多個英文逗號分割").split(","));
? ? ? strategy.setControllerMappingHyphenStyle(true);
? ? ? strategy.setTablePrefix("m_");
? ? ? mpg.setStrategy(strategy);
? ? ? mpg.setTemplateEngine(new FreemarkerTemplateEngine());
? ? ? mpg.execute();
? }
}
右鍵運行CodeGenerator生成代碼
運行之后,就會讀取我們數(shù)據(jù)庫的配置,根據(jù)里面的表,自動生成service、mapper、controller、xml文件等代碼了。
輸入表名,多個表用英文的逗號分隔,最后敲回車就行

這就是我們的代碼生成好的結(jié)果

特別注意事項
大家在生成代碼之前,一定要把數(shù)據(jù)庫設(shè)計好,包括:表名、表字段類型等等,都要考慮好,不然代碼生成之后,后續(xù)想要修改數(shù)據(jù)庫,重新修改代碼是一件很麻煩的事
后續(xù)操作
想要運行代碼,我們還需要一些配置
在yml文件中加入數(shù)據(jù)庫的配置和xml文件的掃描路徑
mybatis-plus: mapper-locations: /classpath*:/mapper/**Mapper.xml ? spring: datasource: ? driver-class-name: com.mysql.cj.jdbc.Driver ? url: jdbc:mysql://localhost:3306/our-task?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai&tinyInt1isBit=false&allowPublicKeyRetrieval=true ? username: daxingyong ? password: daxingyong
由于還需要掃描mapper的路徑,所以需要在SpringBoot的啟動類上,加入@MapperScan("com.example.demo.mapper"),其中引號里面是我們的mapper文件的存放路徑
package com.example.demo;
?
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
?
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
? public static void main(String[] args) {
? ? ? SpringApplication.run(DemoApplication.class, args);
? }
}
以上就是Mybatis-Plus實現(xiàn)自動生成代碼的操作步驟的詳細內(nèi)容,更多關(guān)于Mybatis-Plus自動生成代碼的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
解決新版 Idea 中 SpringBoot 熱部署不生效的問題
這篇文章主要介紹了解決新版 Idea 中 SpringBoot 熱部署不生效的問題,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08
springboot使用alibaba的druid數(shù)據(jù)庫連接池錯誤的問題及解決
這篇文章主要介紹了springboot使用alibaba的druid數(shù)據(jù)庫連接池錯誤的問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
SpringBoot異步Async使用Future與CompletableFuture區(qū)別小結(jié)
本文主要介紹了SpringBoot異步Async使用Future與CompletableFuture區(qū)別小結(jié),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
全面理解java中的構(gòu)造方法以及this關(guān)鍵字的用法
本篇文章主要概述了如何用構(gòu)造方法初始化對象,this屬性名訪問成員變量方法,和this()的用法,感興趣的小伙伴一起來學(xué)習(xí)吧2023-03-03
關(guān)于JDK源碼中的@author unascribed注釋閑談
這篇文章主要介紹了關(guān)于JDK源碼中的@author unascribed注釋閑談,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08

