最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

更簡單更高效的Mybatis?Plus最新代碼生成器AutoGenerator

 更新時間:2023年02月10日 14:59:19   作者:austin流川楓  
這篇文章主要為大家介紹了更簡單更高效的Mybatis?Plus最新代碼生成器AutoGenerator使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

正文

MyBatis-Plus(簡稱 MP)是一個 MyBatis 的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發(fā)、提高效率而生。

今天的主角是MP推出的一款代碼生成器,本文主要來介紹一下它強大的代碼生成功能。

一、概述

AutoGeneratorMyBatis Plus推出的代碼生成器,可以快速生成Entity、Mapper、Mapper XMLService、Controller等各個模塊的代碼,比Mybatis Generator更強大,開發(fā)效率更高。

以往我們使用mybatis generator生成代碼正常需要配置mybatis-generator-config.xml,代碼配置比較繁瑣復雜,比如:

<generatorConfiguration>
    <context id="myContext" targetRuntime="MyBatis3" defaultModelType="flat">
        <!-- 注釋 -->
        <commentGenerator>
            <!-- 是否不生成注釋 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!-- jdbc連接 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://ip:3306/codingmoretiny02?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai&amp;useSSL=false"
                        userId="codingmoretiny02"
                        password="123456">
            <!--高版本的 mysql-connector-java 需要設置 nullCatalogMeansCurrent=true-->
            <property name="nullCatalogMeansCurrent" value="true"/>
        </jdbcConnection>
        <!-- 類型轉(zhuǎn)換 -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="true"/>
        </javaTypeResolver>
        <!-- 生成實體類地址 -->
        <javaModelGenerator targetPackage="com.codingmore.mbg.po" targetProject="src/main/java">
            <!-- 是否針對string類型的字段在set方法中進行修剪,默認false -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成Mapper.xml文件 -->
        <sqlMapGenerator targetPackage="com.codingmore.mbg.mapper" targetProject="src/main/resources">
        </sqlMapGenerator>
        <!-- 生成 XxxMapper.java 接口-->
        <javaClientGenerator targetPackage="com.codingmore.mbg.dao" targetProject="src/main/java" type="XMLMAPPER">
        </javaClientGenerator>
        <table schema="" tableName="user" domainObjectName="User"
               enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
               enableUpdateByExample="false" selectByExampleQueryId="false">
        </table>
    </context>
</generatorConfiguration>

二、使用AutoGenerator

1. 初始化數(shù)據(jù)庫表結(jié)構(gòu)(以User用戶表為例)

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '用戶名',
  `mobile` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '手機號',
  `create_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '創(chuàng)建人',
  `create_time` datetime(0) NULL DEFAULT NULL COMMENT '創(chuàng)建時間',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `username`(`username`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用戶' ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;

2. 在 pom.xml 文件中添加 AutoGenerator 的依賴。

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.1</version>
</dependency>

3. 添加模板引擎依賴

MyBatis-Plus 支持 Velocity(默認)、Freemarker、Beetl,這里使用Freemarker引擎。

<dependency>
   <groupId>org.freemarker</groupId>
   <artifactId>freemarker</artifactId>
   <version>2.3.31</version>
</dependency>

4. 全局配置

package com.shardingspherejdbc.mybatisplus.genertor;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.baomidou.mybatisplus.generator.fill.Property;
import com.shardingspherejdbc.mybatisplus.engine.EnhanceFreemarkerTemplateEngine;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
 * 代碼生成器
 *
 * @author: austin
 * @since: 2023/2/6 15:28
 */
public class CodeGenerator {
    public static void main(String[] args) {
        // 數(shù)據(jù)源配置
        FastAutoGenerator.create("jdbc:mysql://localhost:3306/sharding-db0?serverTimezone=GMT%2B8", "root", "admin")
                .globalConfig(builder -> {
                    builder.author("austin")        // 設置作者
                            .enableSwagger()        // 開啟 swagger 模式 默認值:false
                            .disableOpenDir()       // 禁止打開輸出目錄 默認值:true
                            .commentDate("yyyy-MM-dd") // 注釋日期
                            .dateType(DateType.ONLY_DATE)   //定義生成的實體類中日期類型 DateType.ONLY_DATE 默認值: DateType.TIME_PACK
                            .outputDir(System.getProperty("user.dir") + "/src/main/java"); // 指定輸出目錄
                })
                .packageConfig(builder -> {
                    builder.parent("com.shardingspherejdbc.mybatisplus") // 父包模塊名
                            .controller("controller")   //Controller 包名 默認值:controller
                            .entity("entity")           //Entity 包名 默認值:entity
                            .service("service")         //Service 包名 默認值:service
                            .mapper("mapper")           //Mapper 包名 默認值:mapper
                            .other("model")
                            //.moduleName("xxx")        // 設置父包模塊名 默認值:無
                            .pathInfo(Collections.singletonMap(OutputFile.xml, System.getProperty("user.dir") + "/src/main/resources/mapper")); // 設置mapperXml生成路徑
                    //默認存放在mapper的xml下
                })
                .injectionConfig(consumer -> {
                    Map<String, String> customFile = new HashMap<>();
                    // DTO、VO
                    customFile.put("DTO.java", "/templates/entityDTO.java.ftl");
                    customFile.put("VO.java", "/templates/entityVO.java.ftl");
                    consumer.customFile(customFile);
                })
                .strategyConfig(builder -> {
                    builder.addInclude("user") // 設置需要生成的表名 可邊長參數(shù)“user”, “user1”
                            .addTablePrefix("tb_", "gms_") // 設置過濾表前綴
                            .serviceBuilder()//service策略配置
                            .formatServiceFileName("%sService")
                            .formatServiceImplFileName("%sServiceImpl")
                            .entityBuilder()// 實體類策略配置
                            .idType(IdType.ASSIGN_ID)//主鍵策略  雪花算法自動生成的id
                            .addTableFills(new Column("create_time", FieldFill.INSERT)) // 自動填充配置
                            .addTableFills(new Property("update_time", FieldFill.INSERT_UPDATE))
                            .enableLombok() //開啟lombok
                            .logicDeleteColumnName("deleted")// 說明邏輯刪除是哪個字段
                            .enableTableFieldAnnotation()// 屬性加上注解說明
                            .controllerBuilder() //controller 策略配置
                            .formatFileName("%sController")
                            .enableRestStyle() // 開啟RestController注解
                            .mapperBuilder()// mapper策略配置
                            .formatMapperFileName("%sMapper")
                            .enableMapperAnnotation()//@mapper注解開啟
                            .formatXmlFileName("%sMapper");
                })
                // 使用Freemarker引擎模板,默認的是Velocity引擎模板
                //.templateEngine(new FreemarkerTemplateEngine())
                .templateEngine(new EnhanceFreemarkerTemplateEngine())
                .execute();
    }
}

5. 自定義模板生成DTO、VO

package com.shardingspherejdbc.mybatisplus.engine;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.springframework.stereotype.Component;
import java.io.File;
import java.util.Map;
/**
 * 代碼生成器支持自定義[DTO\VO等]模版
 *
 * @author: austin
 * @since: 2023/2/9 13:00
 */
@Component
public class EnhanceFreemarkerTemplateEngine extends FreemarkerTemplateEngine {
    @Override
    protected void outputCustomFile(Map<String, String> customFile, TableInfo tableInfo, Map<String, Object> objectMap) {
        String entityName = tableInfo.getEntityName();
        String otherPath = this.getPathInfo(OutputFile.other);
        customFile.forEach((key, value) -> {
            String fileName = String.format(otherPath + File.separator + entityName + "%s", key);
            this.outputFile(new File(fileName), objectMap, value, true);
        });
    }
}

未生成代碼前的項目目錄如下:

運行CodeGenerator生成代碼:

14:20:21.127 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================準備生成文件...==========================
14:20:22.053 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 執(zhí)行SQL:show table status WHERE 1=1  AND NAME IN ('user')
14:20:22.081 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 返回記錄數(shù):1,耗時(ms):26
14:20:22.167 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 執(zhí)行SQL:show full fields from `user`
14:20:22.171 [main] WARN com.baomidou.mybatisplus.generator.IDatabaseQuery$DefaultDatabaseQuery - 當前表[user]的主鍵為自增主鍵,會導致全局主鍵的ID類型設置失效!
14:20:22.182 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 返回記錄數(shù):5,耗時(ms):14
14:20:22.502 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================文件生成完成?。?!==========================

項目成功生成了Entity、Service、Controller、Mapper、Mapper.xml、DTO、VO文件。

User用戶類

package com.shardingspherejdbc.mybatisplus.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.Date;
/**
 * <p>
 * 用戶
 * </p>
 *
 * @author austin
 * @since 2023-02-09
 */
@Getter
@Setter
@TableName("user")
@ApiModel(value = "User對象", description = "用戶")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    @ApiModelProperty("用戶名")
    @TableField("username")
    private String username;
    @ApiModelProperty("手機號")
    @TableField("mobile")
    private String mobile;
    @ApiModelProperty("創(chuàng)建人")
    @TableField("create_by")
    private String createBy;
    @ApiModelProperty("創(chuàng)建時間")
    @TableField(value = "create_time", fill = FieldFill.INSERT)
    private Date createTime;
}

想了解MyBatis Plus代碼生成配置可以參考官方配置:代碼生成器配置新

總結(jié)

對比MybatisGeneratorMyBatis-PlusAutoGenerator,就可以得出這樣一條結(jié)論:后者的配置更簡單,開發(fā)效率也更高,功能也更強大——可快速生成Mapper、Model、Service、Controller、DTO/VO層代碼,到這里AutoGenerator生成器的介紹已經(jīng)完成

以上就是更簡單更高效的Mybatis Plus最新代碼生成器AutoGenerator的詳細內(nèi)容,更多關于Mybatis Plus代碼生成器的資料請關注腳本之家其它相關文章!

相關文章

  • 什么是Maven及如何配置國內(nèi)源實現(xiàn)自動獲取jar包的操作

    什么是Maven及如何配置國內(nèi)源實現(xiàn)自動獲取jar包的操作

    本文介紹了Maven的基本概念,包括項目構(gòu)建、依賴管理、倉庫管理以及如何設置國內(nèi)源,通過Maven,開發(fā)者可以自動化管理項目的依賴和構(gòu)建流程,提高開發(fā)效率,感興趣的朋友跟隨小編一起看看吧
    2024-11-11
  • Java中使用開源庫JSoup解析HTML文件實例

    Java中使用開源庫JSoup解析HTML文件實例

    這篇文章主要介紹了Java中使用開源庫JSoup解析HTML文件實例,Jsoup是一個開源的Java庫,它可以用于處理實際應用中的HTML,比如常見的HTML格式化就可以用它來實現(xiàn),需要的朋友可以參考下
    2014-09-09
  • Java實現(xiàn)圖片裁剪功能的示例詳解

    Java實現(xiàn)圖片裁剪功能的示例詳解

    這篇文章主要介紹了如何利用Java實現(xiàn)圖片裁剪功能,可以將圖片按照自定義尺寸進行裁剪,文中的示例代碼講解詳細,感興趣的可以了解一下
    2022-01-01
  • Java 數(shù)組分析及簡單實例

    Java 數(shù)組分析及簡單實例

    這篇文章主要介紹了Java 數(shù)組分析及簡單實例的相關資料,在Java中它就是對象,一個比較特殊的對象,需要的朋友可以參考下
    2017-03-03
  • 實例詳解Java中如何對方法進行調(diào)用

    實例詳解Java中如何對方法進行調(diào)用

    這篇文章主要介紹了實例詳解Java中如何對方法進行調(diào)用,是Java入門學習中的基礎知識,需要的朋友可以參考下
    2015-10-10
  • java操作PDF文件方法之轉(zhuǎn)換、合成、切分

    java操作PDF文件方法之轉(zhuǎn)換、合成、切分

    最近需要做?個把多個pdf報告合并成?個以?便預覽的需求,下面這篇文章主要給大家介紹了關于java操作PDF文件方法之轉(zhuǎn)換、合成、切分的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2024-01-01
  • 詳解關于java文件下載文件名亂碼問題解決方案

    詳解關于java文件下載文件名亂碼問題解決方案

    這篇文章主要介紹了詳解關于java文件下載文件名亂碼問題解決方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-01-01
  • 詳解簡單基于spring的redis配置(單機和集群模式)

    詳解簡單基于spring的redis配置(單機和集群模式)

    這篇文章主要介紹了詳解簡單基于spring的redis配置(單機和集群模式),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-02-02
  • Java通過 Socket 實現(xiàn) TCP服務端

    Java通過 Socket 實現(xiàn) TCP服務端

    這篇文章主要介紹了Java通過 Socket 實現(xiàn) TCP服務端的相關資料,需要的朋友可以參考下
    2017-05-05
  • Mybatis-plus插入后返回元素id的問題

    Mybatis-plus插入后返回元素id的問題

    這篇文章主要介紹了Mybatis-plus插入后返回元素id的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03

最新評論

澎湖县| 扬中市| 土默特左旗| 蓬溪县| 昔阳县| 临邑县| 乌鲁木齐县| 长顺县| 九江市| 瓮安县| 二连浩特市| 宾川县| 涟水县| 东阿县| 新乡县| 兴国县| 蒙自县| 赫章县| 红安县| 宁南县| 宣恩县| 苏州市| 伊金霍洛旗| 平阳县| 泗阳县| 高清| 绥宁县| 五寨县| 堆龙德庆县| 女性| 峨眉山市| 巴东县| 苏尼特左旗| 苗栗市| 田东县| 洪泽县| 麻阳| 仲巴县| 庆安县| 西乌| 新田县|