Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

📖 preface

Good attitude, not so tired. In a good mood, all you see is beautiful scenery.Copy the code

"If you can't solve a problem for a while, use this opportunity to see your limitations and put yourself out of order." As the old saying goes, it's easy to let go. If you are distracted by something, learn to disconnect. Cut out the paranoia, the trash in the community, and get rid of the negative energy. Good attitude, not so tired. In a good mood, all you see is beautiful scenery.

PS: A Gradle version of the generator is available first, and I will integrate it into the SpringCloud project later.

🚀 go firstgitaddress

portal

🚓 get down to business

1. I won’t go into creating projects

2. Introduce dependencies, as shown belowMavenThere is also a later version

Plugins {id 'java-library' id 'org.springframework.boot' version '2.2.1.RELEASE' id 'io.spring.dependency-management' RELEASE'} group 'com.cyj. codeGen 'version '1.0.0' apply plugin: 'idea' apply plugin: 'java-library' apply plugin: 'io.spring.dependency-management' apply plugin: 'org.springFramework. boot' // Specify JDK version sourceCompatibility = javUncomfortable.VERSION_1_8 targetCompatibility = JavaVersion. VERSION_1_8 / / specified coding format [compileJava compileTestJava, javadoc] *. The options *. Encoding = "utf-8" / / / / the source file configuration SourceSets. Main. Resources. SrcDirs = [" SRC/main/Java ", "SRC/main/resources"] / / the source file configuration sourceSets {main { java.srcDir('src/main/java') resources.srcDir('src/main/resources') } test { java.srcDir('src/test/java') Resources. SrcDir (' SRC /test/resources')}} sourceCompatibility = 1.8TargetCompatibility = 1.8repositories { mavenLocal() maven { url 'https://maven.aliyun.com/repository/public/' } maven { url 'https://oss.sonatype.org/content/repositories/snapshots/'} mavenCentral ()} / / rely on the version number of the unified control ext {springBootVar = RELEASE' springBootMybatis' = '2.1.3' httpClient = '4.5.2' mysql = '5.1.21' junit = '4.12' fastJson = '1.2.75' DruidVer = '1.1.21' Swagger2 = '2.9.2' swagger2UI = '2.9.2' = 'mid-atlantic moved' = '1.9.6' swaggerBootstrapUI knife4j} dependencies {the compile (' org.apache.com mons: the Commons - lang3:3.11) The compile (' org.apache.com mons: the Commons - collections4:4.4 ') / / introduction of mybatis - plus depend on the package Compile ('com.baomidou:mybatis-plus-boot-starter:3.3.2') // import the SpringBootWeb dependency package The compile (" org. Springframework. The boot: spring - the boot - starter - web: ${springBootVar} ") / / SpringBoot core rely on introduction The compile (" org. Springframework. The boot: spring - the boot - starter: ${springBootVar} ") {/ / exclude tomcat exclude the module: "Tomcat-embed -el"} // SpringBootMybatis dependency import The compile (" org. Mybatis. Spring. The boot: mybatis - spring - the boot - starter: ${springBootMybatis} ") / / httpclient related dependency The compile (" org. Apache httpcomponents: httpclient: ${httpclient} ") / / introduction of the database link drive mysql connector - Java dependency Compile ("mysql:mysql-connector-java") // import SpringDataJpa dependencies The compile (" org. Springframework. The boot: spring - the boot - starter - data - jpa: ${springBootVar} ") / / introducing the Druid The compile (" com. Alibaba: druid - spring - the boot - starter: ${druidVer} ") / / into the pool depend on the compile (" org.apache.com mons: Commons - pool2 ") Compile (" IO. Springfox: springfox-Swagger2 :${swagger2}" Compile (" IO. Springfox: springfox-Swagger-ui :${swagger2UI}") // introduce optimized swagger2UI dependencies https://xiaoym.gitee.io/knife4j/documentation compile("com.github.xiaoymin:knife4j-spring-boot-starter:${knife4j}") // Dynamic compile('com.baomidou:dynamic-datasource-spring-boot-starter:3.3.2') // Compile jasypt dependency package // The compile (' org. Jasypt: jasypt: 1.9.2 ') implementation 'Commons - configuration: the Commons - the configuration: 1.10' implementation 'org. Apache. Velocity, velocity: 1.7' / / json related depend on the compile (" com. Alibaba: fastjson: ${fastjson} ") implementation "com.google.guava:guava:${guava}" implementation "cn.hutool:hutool-all:${hutoolVersion}" compileOnly 'javax.mail. Servlet: javax.mail. Servlet - API: 4.0.1' implementation 'org. Springframework. The boot: spring - the boot - configuration - processor' / / Database password encryption implementation 'com. Making. Ulisesbocchio: jasypt - spring - the boot - starter: 2.1.0' implementation 'org.springframework.boot:spring-boot-starter-actuator' testImplementation 'org.springframework.boot:spring-boot-starter-test' compileOnly 'org.projectlombok:lombok' annotationProcessor 'org.projectLombok :lombok'} // Modify gradle build encoding to UTF-8 tasks.withType(JavaCompile) {options.encoding = "utF-8"} test { useJUnitPlatform() }Copy the code

3. Change the startup class – the location of the scanned Mapper

package com.cyj.codegen;

import cn.hutool.core.date.DateUtil;
import com.cyj.codegen.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/ * * *@Description: Startup class *@BelongsProject: MybatisPlusCodeGenDemo
 * @BelongsPackage: com.cyj.codegen
 * @Author: ChenYongJia
 * @CreateTime: the 2021-09-03 09:41 *@Email: [email protected]
 * @Version: 1.0 * /
@Slf4j
@MapperScan("com.cyj.codegen.mapper")
@SpringBootApplication(scanBasePackages = {Constants.SCAN_BASE_PACKAGES})
public class CodeGenApplication {

    /** * Project startup method **@param args the input arguments
     * @dateThe 2021-9-3 14:15:42 *@author Sunny Chen
     */
    public static void main(String[] args) {
        log.info("Mybatis- Plus code Generator project starts ing! = = = = = = > {}", DateUtil.now());
        SpringApplication.run(CodeGenApplication.class, args);
        log.info("Mybatis- Plus code generator project started successfully ing....... ! = = = = = = > {}", DateUtil.now()); }}Copy the code

4. Create a database — execute the static resourcepig_codegen.sqlfile

5. Add a sexy onebanner.txtYou are a good boy

   _  _                                                              __ _                      _             _                _  _
  | || |   ___    _  _      o O O  __ _      _ _    ___      o O O  / _` |   ___     ___    __| |     o O O | |__     ___    | || |
   _, |  / _ \  | +| |    o      / _` |    | '_| / -_) o __, | / _ \ / _ \ / _` | o | '_ \   / _ \    _, |
  _|__/   ___/   _,_|   TS__[O] __,_|   _|_|_   ___|   TS__[O]  |___/   ___/   ___/  __,_|   TS__[O] |_.__/   ___/   _|__/
_| """"| | -"""""| | -"""""| {= = = = = = | _ |"""""| | -"""""| | -"""""| {= = = = = =" | | -""""| | -"""""| | -"""""| | -"""""| {= = = = = =" | | -""""| | -"""""| | -""""|"` -0-0-'" ` - 0-0 -'"`-0-0-'./o--000'"` -0-0-'" ` - 0-0 -'"`-0-0-'./o--000'"` -0-0-'" ` - 0-0 -'"` - 0-0 - '"` -0-0-'./o--000'"` - 0-0 - '"` -0-0-'" ` - 0-0 -'
Copy the code

6. Create a database global constant classDataSourceConstants 和 Constants

Note that change the DS_DRIVER parameter to distinguish between 5.7.x and 8.0.x, and change the SCAN_BASE_PACKAGES parameter to scan your package path

package com.cyj.codegen.common;

/ * * *@Description: Database constant *@BelongsProject: MybatisPlusCodeGenDemo
 * @BelongsPackage: com.cyj.codegen.common
 * @Author: ChenYongJia
 * @CreateTime: the 2021-09-03 joyfully *@Email: [email protected]
 * @Version: 1.0 * /
public interface DataSourceConstants {

    /** * Data source name */
    String DS_NAME = "name";

    /** * default driver --mysql8 + cj */
    String DS_DRIVER = "com.mysql.cj.jdbc.Driver";

    /** * Default data source (master) */
    String DS_MASTER = "master";

    /** * jdbcurl */
    String DS_JDBC_URL = "url";

    /** * User name */
    String DS_USER_NAME = "username";

    /** * Password */
    String DS_USER_PWD = "password";

}
Copy the code

7. Verify exception classesCheckedException

@NoArgsConstructor
public class CheckedException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public CheckedException(String message) {
        super(message);
    }

    public CheckedException(Throwable cause) {
        super(cause);
    }

    public CheckedException(String message, Throwable cause) {
        super(message, cause);
    }

    public CheckedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace); }}Copy the code

Configuration of 8.SwaggerI won’t go into it

In 9.modelNext create the entity class

ColumnEntity object -- Generator configures entity object --GenConfig, multi-data source --GenDatasourceConf, generates record table --GenFormConf, Table properties --TableEntity

PS: The combination forms the basic production infrastructure.

10. serviceThe layer is used to implement basic operations such as add, delete, change, and review of these classes

11. Code generator help class —CodeGenUtilsFocus on

The getTemplates method is used to get the configuration — that is, the.vm generation template we wrote. The generatorCode method is used to generate code, the renderData method is used to renderData, and the columnToJava method is used to convert table names to Java class names The getConfig method is used to get our configuration information. The getFileName method is used to get the file name

12. Under the allocation of resourcestemplate

The inside of the.vmApproved in the filevelocityTo obtain the variable name, more usage can be used by baidu query.

13. Of course, please pay attention to the modificationgenerator.propertiesThe package path and data type in the file

14. Demonstrate the generated code

Due to space reasons, only code generation is demonstrated here, the other interfaces are also given you can test to see the effect

Finally, thank you for your patience to watch the end, the original is not easy, leave a point like collection is your biggest encouragement to me!


🎉 summary:

  • For more references, see here:The Blog of Chan Wing Kai

  • I hope these codes can help you lighten up a littlecrudBurden, and some inspiration.

  • Like the small partner of the blogger can add a concern, a thumbs-up oh, continue to update hey hey!