代碼一鍵自動生成,拿走不謝

程序猿學社的GitHub,歡迎Star
github技術專題
本文已記錄到github

前言

隔壁老王: 社長,我工作有一段時間咯,我看其他的同事,上班都很悠閒,而且,那些實體類,感覺有模板似的,有點像機器生成的,是不是有什麼工具,可以自動生成代碼。
社長: 有的,嘻嘻,MP的AutoGenerator 插件,一鍵生成代碼,並且,可以集成swagger,加上對應的註釋,大大提高你的開發效率。
隔壁老王: 這麼優秀,難怪,我看我們項目組的那些人,這麼多時間撩妹。

起源

社長剛剛開始工作的時候,那時候,dao,entity,service,controller都要自己去編寫。而這部分代碼,都是有一定的規範,有需求,就有對應的產品應運而生,AutoGenerator 是 MyBatis-Plus 的代碼生成器,通過 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各個模塊的代碼,極大的提升了開發效率。

環境

springboot 2.2.6.RELEASE
mybatis-plus 3.3.0
spring-boot-starter-swagger 1.5.1.RELEASE

  • 環境版本最好保持一致,不然,你可以收穫意外的驚喜

實戰

  • 如遇到不清楚的,文件如何存放的,可以參考我的結構

sql腳本

/*
 Navicat Premium Data Transfer

 Source Server         : 本地
 Source Server Type    : MySQL
 Source Server Version : 50722
 Source Host           : localhost:3306
 Source Schema         : pro

 Target Server Type    : MySQL
 Target Server Version : 50722
 File Encoding         : 65001

 Date: 05/04/2020 19:17:01
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (
  `id` int(111) NOT NULL AUTO_INCREMENT COMMENT '編號',
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名',
  `age` int(11) NULL DEFAULT NULL COMMENT '年齡',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES (1, '社長', 18);
INSERT INTO `student` VALUES (2, '老王', 20);
INSERT INTO `student` VALUES (3, '蘭陵王', 11);

SET FOREIGN_KEY_CHECKS = 1;

pom.xml

<?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.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.cxyxs</groupId>
    <artifactId>auto</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>auto</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--web依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--junit測試-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.0</version>
        </dependency>

        <!--代碼生成模式插件  3.0.3以後需要手動設置依賴-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>

        <!--代碼生成模板-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.2</version>
        </dependency>

        <!--簡化代碼插件-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!--mysql驅動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>

        <!-- druid阿里巴巴數據庫連接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.6</version>
        </dependency>

        <!-- 熱部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

        <!--swagger2-->
        <dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>spring-boot-starter-swagger</artifactId>
            <version>1.5.1.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <!--打包後的項目名-->
        <finalName>codeauto</finalName>
        <!--解決mapper文件不到class文件夾的問題-->
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src\main\java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>


        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <!-- 1、設置jar的入口類 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>com.cxyxs.auto.AutoApplication</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>


            <!--2、把附屬的jar打到jar內部的lib目錄中 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>


            <!-- 3、打包過程忽略Junit測試 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
  • MyBatis-Plus 從 3.0.3 之後移除了代碼生成器與模板引擎的默認依賴,需要手動添加相關依賴:
  • 爲方便以後前後端對接,集成了swagger
  • 可達成jar包,直接build就行,build裏面的配置,就是爲了打成jar包

application.yml

server:
  port: 8888

spring:
  datasource:
    # 配置數據源
    driver-class-name: com.mysql.cj.jdbc.Driver
    # 使用druid連接池
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://127.0.0.1:3306/pro?useUnicode=true&characterEncoding=utf8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
    username: root
    password: root

###增加日誌輸出,方便定位問題
logging:
  level:
    root : warn
    com.cxyxs.mybatisplus.dao: trace
  ###控制檯輸出格式
  pattern:
    console: '%p%m%n'

mybatis-plus:
  mapper-locations: classpath*:/com/cxyxs/auto/mapper/xml/*.xml
  global-config:
    db-config:
      ###邏輯未刪除的值
      logic-not-delete-value: 0
      ###邏輯已刪除的值
      logic-delete-value: 1


  ####掃描swagger註解
  swagger:
    base-package: com.cxyxs
  • 配置數據庫的信息,以自己的配置爲主
  • mapper-locations 是根據自動生成代碼的規則而定義的
  • swagger 配置swagger註解,掃描範圍

啓動類

package com.cxyxs.auto;

import com.spring4all.swagger.EnableSwagger2Doc;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.cxyxs.auto.mapper")
@EnableSwagger2Doc
public class AutoApplication {

    public static void main(String[] args) {
        SpringApplication.run(AutoApplication.class, args);
    }
}
  • @MapperScan配置掃描dao包的位置(以我們常用的思維),社長習慣以mapper命名
  • @EnableSwagger2Doc 啓用swagger註解

代碼自動生成

package com.cxyxs.auto;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.List;

/**
 * Description:
 * Author: wude
 * Date:  2020/4/5 9:14
 * Modified By:
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class CodeGenerationTests {
    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("程序猿學社");    //設置作者
        //生成代碼後,是否打開文件夾
        gc.setOpen(false);
        gc.setFileOverride(false);  //是否覆蓋原來代碼,個人建議設置爲false,別覆蓋,危險係數太高
        gc.setServiceName("%sService");   //去掉service的I前綴,一般只需要設置service就行
/*        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");*/

        gc.setDateType(DateType.ONLY_DATE);   //日期格式
        gc.setSwagger2(true);       // 實體屬性 Swagger2 註解,實體類上會增加註釋
        mpg.setGlobalConfig(gc);

        // 數據源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/pro?useUnicode=true&characterEncoding=utf8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        dsc.setDbType(DbType.MYSQL);    //指定數據庫的類型
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.cxyxs.auto");   //自定義包的路徑
        //pc.setModuleName("module");   //模塊名稱  設置後,會生成com.cxyxs.test.module,裏面存放之前設置的mapper,entity
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setController("controller");
        mpg.setPackageInfo(pc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("student");    //設置映射的表名,可以設置多個表

        //表前綴設置  cxyxs_student
        //strategy.setTablePrefix(new String[]{"cxyxs_"});
        //包的命名規則,使用駝峯規則
        strategy.setNaming(NamingStrategy.underline_to_camel);
        //列的名稱,使用駝峯規則
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //是否使用lombok
        strategy.setEntityLombokModel(true);
        //駝峯命名
        strategy.setRestControllerStyle(true);
        strategy.setLogicDeleteFieldName("is_delete");   //邏輯刪除,假刪除會用到

        //自動填充字段,在項目開發過程中,例如創建時間,修改時間,每次,都需要我們來指定,太麻煩了,設置爲自動填充規則,就不需要我們賦值咯
        TableFill fillInsert = new TableFill("create_time", FieldFill.INSERT);
        TableFill fillUpdate= new TableFill("update_time", FieldFill.UPDATE);
        List fillLists = new ArrayList();
        fillLists.add(fillInsert);
        fillLists.add(fillUpdate);
        strategy.setTableFillList(fillLists);
        //樂觀鎖
        //strategy.setVersionFieldName("version");
        mpg.setStrategy(strategy);

        mpg.execute();  //執行
    }
}

直接啓動main方法 ,見證奇蹟的時候到咯。

  • contoller,entity,mapper,service代碼都給我們生成好咯。
  • swagger註釋都給我們生成好咯,而且代碼也很規範,讓我們自己來寫,可能會遇到很多很低級的錯誤。
  • 雖說,代碼自動生成很智能,智能的前提,是有規範的,數據庫命令,最高遵守相關的規範,這裏就不過多闡述咯

controller類

package com.cxyxs.auto.controller;


import com.cxyxs.auto.entity.Student;
import com.cxyxs.auto.mapper.StudentMapper;
import com.cxyxs.auto.util.Result;
import io.swagger.annotations.ApiOperation;
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 程序猿學社
 * @since 2020-04-05
 */
@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentMapper studentMapper;

    @GetMapping("/test")
    @ApiOperation(value = "測試接口",notes = "測試")
    public List<Student> getStudent1(Student stu){
        List<Student> lists = studentMapper.selectList(null);
        return lists;
    }
}
  • StudentController這個類,是自動生成的,增加一個方法,來看看效果。

測試

http://localhost:8888/swagger-ui.html

  • 通過頁面可以發現有一個basic-error-controller,實際上,我們代碼裏面沒有定義這個,有強迫症的,可以百度解決方法,配置一下,這裏社長,就不配置咯。
  • 通過可視化界面,前端可以看到返回的參數註釋
  • 傳參也有註釋

點擊try it out按鈕

  • 跟前端需要對接的傳參和返回參數都有註釋,那個接口,用來幹嘛的,都有註釋文檔。就沒有後臺什麼事咯

原創不易,不要白嫖,覺得有用的社友,給我點贊,讓更多的老鐵看到這篇文章。
因技術能力有限,如文中有不合理的地方,希望各位大佬指出,在下方評論留言,謝謝,希望大家一起進步,一起成長。

作者:程序猿學社
原創公衆號:『程序猿學社』,專注於java技術棧,分享java各個技術系列專題,以及各個技術點的面試題。
原創不易,轉載請註明來源(註明:來源於公衆號:程序猿學社, 作者:程序猿學社)。

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