MybatisPlu自動生成CRUD接口(二)

作爲一個有一定經驗開發人員,一定不希望自己每天都在做簡單CRUD操作,這樣其實只是在浪費自己的時間,那麼有沒有什麼工具讓我們自動生成對數據庫的CRUD操作啦?答案是肯定的,下面我們就介紹下如何通過MyBatisPlu中自定義模板(根據自己公司的基本需求)實現符合公司基本要求的CRUD接口(可以直接和前端聯調的接口)。

話不多說直接講實現:

首先我們要新建一個Maven搭建的SpringBoot項目

下面是我項目中用到的依賴(新建Maven項目複製如下依賴集合),

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.6.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<properties>
		<maven-jar-plugin.version>3.1.0</maven-jar-plugin.version>
	</properties>
  <dependencies>
  	    <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
      <!-- 數據庫相關依賴 -->
       <dependency>
		    <groupId>com.alibaba</groupId>
		    <artifactId>druid</artifactId>
		    <version>1.1.16</version>
		</dependency>
		<dependency>
		    <groupId>mysql</groupId>
		    <artifactId>mysql-connector-java</artifactId>
		   <version>8.0.11</version>
		</dependency>
		<!-- 數據庫相關依賴 -->
		
		<!--添加 代碼生成器 相關依賴-->
		<dependency>
		    <groupId>com.baomidou</groupId>
		    <artifactId>mybatis-plus-generator</artifactId>
		    <version>3.2.0</version>
		</dependency>
		<dependency>
		    <groupId>org.mybatis.spring.boot</groupId>
		    <artifactId>mybatis-spring-boot-starter</artifactId>
		    <version>1.1.1</version>
		</dependency>

		<dependency>
		   <groupId>org.projectlombok</groupId>
		   <artifactId>lombok</artifactId>
		</dependency>
		<dependency>
		    <groupId>org.freemarker</groupId>
		    <artifactId>freemarker</artifactId>
		    <version>2.3.29</version>
		</dependency>
		<!--添加 代碼生成器 依賴-->
		
		<!-- fastjson依賴 -->
		<dependency>
		    <groupId>com.alibaba</groupId>
		    <artifactId>fastjson</artifactId>
		    <version>1.2.52</version>
		</dependency>
		<!-- 分頁工具 -->
		<dependency>
		    <groupId>com.github.pagehelper</groupId>
		    <artifactId>pagehelper</artifactId>
		    <version>5.1.9</version>
		</dependency>
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper-spring-boot-autoconfigure</artifactId>
			<version>1.2.5</version>
		</dependency>
		<!-- 分頁工具 -->
  </dependencies>

下面我們就要將如何利用MyBatisPlu生成代碼實體類,大致的代碼流程,

1、配置項目模塊名稱,要進行代碼生成的表

2、進行全局配置(配置代碼生成地址,類和接口的名字)

3、進行數據源的配置(基本的數據庫URL,用戶名和密碼)

4、包配置

5、進行模板配置(自己定義的CRUD的方法),需要了解(Freemarker基本使用),後面會做簡單的使用講解,這一步是非常重要的一步。

6、配置基本的策略信息

public static void main(String[] args) {
				//  模塊名
				  String moduleName = "guess";
				//  表名,多個英文逗號分割
				  String tableName = "guess_account,guess_bet_settle";
				  // 代碼生成器
				  AutoGenerator mpg = new AutoGenerator();
				  // 全局配置
				  GlobalConfig gc = new GlobalConfig();
				  String projectPath = System.getProperty("user.dir");
				  gc.setOutputDir(projectPath + "/src/main/java");
				  gc.setAuthor("jack");
				  //設置對象的名稱
				  gc.setEntityName("%s");//實體類命名
				  gc.setMapperName("%sMapper");//dao層接口命名
				  gc.setXmlName("%sMapper");//XML文件命名
				  gc.setServiceName("%sService");//Service層接口命名
				  gc.setServiceImplName("%sServiceImpl");//Service實現層命名
				  gc.setControllerName("%sController");
				  gc.setBaseColumnList(true);//設置XML自動生成表基本字段
				  gc.setBaseResultMap(true);//基本ResultMap
				  gc.setIdType(IdType.AUTO);//設置主鍵策略爲(自增長)
				  // 生成後打開目錄
				  gc.setOpen(false);
				 // gc.setSwagger2(true);// 實體屬性 Swagger2 註解
				  mpg.setGlobalConfig(gc); 
				  // 數據源配置
				  DataSourceConfig dsc = new DataSourceConfig();
				  dsc.setUrl("jdbc:mysql://localhost:3306/citex_guess?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8");
				  dsc.setDriverName("com.mysql.cj.jdbc.Driver");
				  dsc.setUsername("jack");
				  dsc.setPassword("jack987");
				  mpg.setDataSource(dsc);
				  // 包配置
				  PackageConfig pc = new PackageConfig();
				  pc.setModuleName(moduleName);
				  pc.setParent("com.hongyu.mybatis");
				  mpg.setPackageInfo(pc);
				
				  // 自定義配置
				  InjectionConfig cfg = new InjectionConfig() {
				      @Override
				      public void initMap() {
				          // to do nothing
				      }
				  };
				  // 模板引擎是 freemarker
				  String templatePath = "templates/mapper.xml.ftl";
				  // 自定義輸出配置
				  List<FileOutConfig> focList = new ArrayList<>();
				  
				  // 自定義配置XML生成的文件夾位置會被優先輸出
				 focList.add(new FileOutConfig(templatePath) {
				      @Override
				      public String outputFile(TableInfo tableInfo) {
				          // 自定義輸出文件名 , 如果你 Entity 設置了前後綴、此處注意 xml 的名稱會跟着發生變化!!
				          return projectPath + "/src/main/resources/com/hongyu/mybatis/" + pc.getModuleName()
				                  + "/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
				      }
				  });
				 // 自定義生成VO對象
				  focList.add(new FileOutConfig("/templates/entityVo.java.ftl") {
				      @Override
				      public String outputFile(TableInfo tableInfo) {
				          // 自定義輸出文件名 , 如果你 Entity 設置了前後綴、此處注意 xml 的名稱會跟着發生變化!!
				          return projectPath + "/src/main/java/com/hongyu/mybatis/" + pc.getModuleName()
				                  + "/entity/vo/" + tableInfo.getEntityName() + "Vo" + StringPool.DOT_JAVA;
				      }
				  });
				  cfg.setFileOutConfigList(focList);
				  mpg.setCfg(cfg);
				  
				
				  // 配置模板
				  TemplateConfig templateConfig = new TemplateConfig();
				  //指定自定義模板路徑,注意不要帶上.ftl/.vm, 會根據使用的模板引擎自動識別
				  templateConfig.setEntity("templates/entity.java");
				  templateConfig.setMapper("templates/mapper.java");
				  templateConfig.setService("templates/service.java");
				  templateConfig.setServiceImpl("templates/serviceImpl.java");
				  templateConfig.setController("templates/controller.java");
				  //一定要設置爲null,否則會在Mapper對應包下面生XML文件(重複XML)
				  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.entityTableFieldAnnotationEnable(true);
				  strategy.setControllerMappingHyphenStyle(true);
				  strategy.setInclude(tableName.split(","));
				// 策略配置
				  
				  mpg.setStrategy(strategy);
				  //設置模板引擎
				  mpg.setTemplateEngine(new FreemarkerTemplateEngine());
				  mpg.execute();
				
			}

下面我們來講解下Freemarker,我想如果要大家從0開始寫模板,可能有點難度,但是如果有基本模板參考,那就是事半功倍了。

首先我告訴大家去哪裏獲取基本模板

我們可以在項目的Maven依賴中找到mybatis-plus-generator包,然後找到對應的包的存儲地址,將jarbao複製出來解壓縮,就能夠獲取到Entity、Xml、Mapper等所有的模板。注意我們這裏只需要後綴爲.ftl的模板(Freemarker模板)。要使用模板,我們需要建立如下文件夾(templates),注意名字建議使用(templates),並將所有.ftl的模板複製到(templates)文件夾下。

下面我們來簡單解讀.ftl文件,我們以controller.java.ftl爲例

package ${package.Controller};


import org.springframework.web.bind.annotation.RequestMapping;

<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>

/**
 * <p>
 * ${table.comment!} 前端控制器
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
</#if>

}
</#if>

${}是Freemarker獲取值得一種方法。

${package.Controller} 獲取Controller層所在包的包名,同理我們可以獲取${package.Service},${package.ServiceImpl}

${table.comment!}獲取數據庫中對錶的註釋(DDL)中有體現,${table.entityPath}獲取實體類的符合駝峯命名規則的名字(例如

表名guess_account   實體類 GuessAccount      ${table.entityPath} :  guessAccount

${entity} :GuessAccount  實體類的名字,${table.mapperName}  mapper的名字  ${table.serviceName} service的名字

<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>

這個是Freemarker中的if...else..的用法。和mybatis的XML文件中的用法相似。

下面介紹模板中如何注入

  @Autowired
    private ${table.serviceName}  ${table.entityPath}Service;

對了,這個需要我們手動在模板中將包進行引入

import ${package.Service}.${table.serviceName};

import org.springframework.beans.factory.annotation.Autowired;

同理,所有的類引用都需要在模板中引入包。

然後代碼的基本和我們正常寫代碼差別不大。.

下面給出entity.java.ftl作爲參考

package ${package.Entity};

<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if swagger2>
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
</#if>
<#if entityLombokModel>
import lombok.Data;
</#if>
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;

/**
 * <p>
 * ${table.comment!}
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@Data  
<#if table.convert>
@TableName("${table.name}")
</#if>
public class ${entity} implements Serializable {

<#if entitySerialVersionUID>
    private static final long serialVersionUID = 1L;
</#if>
 <#list table.fields as field>
	<#if "${field.propertyType}"?index_of("Date")!=-1>
	  @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") 
	  private Date ${field.propertyName};
	<#else>
      private ${field.propertyType} ${field.propertyName};
	</#if> 
</#list>
 
}

如果想獲取完整的項目,需要通過鏈接https://download.csdn.net/download/weixin_42324471/11973061獲取

下面展示實現效果

PostMan實現效果

查詢所有

按條件分頁查詢

還有基本的增刪,根據主鍵批量刪除,批量添加,根據條件刪除,根據條件更新等操作就不逐一展示。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章