1. 程式人生 > 其它 >Spring boot 整合MyBatis-Plus,逆向工程生成Mapper、Controller、Model等

Spring boot 整合MyBatis-Plus,逆向工程生成Mapper、Controller、Model等

這裡先感謝博主:https://blog.csdn.net/qq_41153943/article/details/107610454 解決了IDEA Error:java:無效的源發行版:11 錯誤 問題

接下來進入我們的本篇部落格感謝環節,感謝博主提供的思路:https://www.cnblogs.com/liuyj-top/p/12976396.html

新建一個SpringBoot專案(教程很多),我的專案目錄如下(請忽略紅線,後面會有問題解決):

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.5.1</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.itcmor</groupId> <artifactId>qsgl</artifactId> <version>0.0.1-SNAPSHOT</
version> <name>qsgl</name> <description>Demo project for Spring Boot</description> <properties> <java.version>8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--<dependency>--> <!--<groupId>com.oracle</groupId>--> <!--<artifactId>ojdbc12</artifactId>--> <!--<version>12.2.0.1.0</version>--> <!--<scope>runtime</scope>--> <!--</dependency>--> <!-- gxq+20210624 MyBatis-plus 逆向生成配置--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.28</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.66</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

2.在src\main\resources下新建一個application.yml檔案,並進行配置。(說實話,我把這個件內容給註釋了也沒啥影響(生成程式碼的java中有連線資料庫的配置),可能是我用的Oracle?不過如果不著急配置一下也不錯,增加點見識

server:
  port: 8088    
  servlet:
    context-path: /

spring:
  datasource:
    driver-class-name: oracle.jdbc.OracleDriver
    url: jdbc:oracle:thin:@localhost:1521:ORCL
    username: ******      # 連線Oracle的使用者
    password: ******      # 連線Oracle的密碼
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
    serialization:
      write-dates-as-timestamps: false

mybatis-plus:
  configuration:
    map-underscore-to-camel-case: true
    auto-mapping-behavior: full
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath*:mapper/**/*Mapper.xml
  global-config:
    db-config:
      logic-not-delete-value: 1
      logic-delete-value: 0 

3.MyBatis-plus分頁外掛配置-就是新建一個.java檔案,我在test\java\com.itcmor.qsgl下新建MyBatisPlusConfig.java

package com.itcmor.qsgl;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfig {
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }
}

4.MyBatis-plus的逆向工程配置(即生成程式碼的配置)-CodeGenerator.java,這借鑑的博主的,應該是基本模式生成,mapper檔案沒有基本的增刪查sql語句(準備使用freemarker模板引擎設定)。

package com.itcmor.qsgl;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
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 com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.InjectionConfig;


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

/**
 * MyBatis-Plus 逆向工程 生成controllor、entity、mapper等程式碼
 */

public class CodeGenerator {
    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 (StringUtils.isNotEmpty(ipt)){   //Mybatis-plus 3.4.3 沒有方法isNotEmpty(),我又改回了博主使用的3.2.0
                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("gxq");
        gc.setOpen(false);

        // 實體屬性 Swagger2 註解
        gc.setSwagger2(false);
        mpg.setGlobalConfig(gc);

        // 資料來源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:oracle:thin:@localhost:1521:ORCL");
        dsc.setDriverName("oracle.jdbc.OracleDriver");
        dsc.setUsername("C##gxq_qs_terminal");
        dsc.setPassword("gxq@2021");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.itcmor.qsgl");
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        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";

        // 自定義輸出配置  (gxq:如若註釋,則按照預設生成)
//        List<FileOutConfig> focList = new ArrayList<>();
        // 自定義配置會被優先輸出
//        focList.add(new FileOutConfig(templatePath) {
//            @Override
//            public String outputFile(TableInfo tableInfo) {
//                // 自定義輸出檔名,如果entity設定了前後綴,此處應注意xml的名稱會跟著發生變化!
//                return projectPath + "/src/main/resources/mybatis/mapper/"
//                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
//            }
//        });
        /*
         cfg.setFileCreate(new IFileCreate() {
             @Override
             public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                 // 判斷自定義資料夾是否需要建立
                 checkDir("呼叫預設方法建立的目錄");
                 return false;
             }
         });
        */
//        cfg.setFileOutConfigList(focList);
//        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定義輸出模板
        // 指定自定義模板路徑,注意不要帶上.ftl/.vm,會根據使用的模板引擎自動識別
        //templateConfig.setEntity("templates/entity2.java");
//        templateConfig.setMapper("/templates/maper.xml.ftl");
        //templateConfig.setService();
        //templateConfig.setController();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置  或者叫資料庫表配置?
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setEntityLombokModel(true);
        // 公共父類
//        strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
        // 寫於父類中的公共欄位
//        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多個英文逗號分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

Ok,右鍵執行這個檔案檔案就行了。假如遇到了JDK版本問題,如Error Java:無目標版本 11,推薦個解決問題的網址,very very感謝作者:https://www.jianshu.com/p/9a3d5258fff8 解決理念:百度到的能改的地方都改了

問題解決環節

1.註解標紅問題1 (找不到@RestController、@RequestMapping),如下圖:

解決:在pom.xml檔案中加入依賴

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.註解標紅問題2 (找不到lombok外掛 @Data、@RestController、@RequestMapping),如下圖:

解決:File-->Settings...-->Plugins,搜尋lombok會發現找不到,然後點選下方的Browse Repositories,如下圖所示,再次搜尋lombok,點選Install

安裝後,在pom.xml檔案中進行配置

<dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
</dependency>

本篇結束,但是mapper沒有滿足需求,接下來摸索freemarker模板-ftl,想著能生成基本的增刪查,由於Mybatis的mapper.xml能生成,希望不僅Mybatis-plus的mapper.xml能生成,其mapper.java也能生成。

Over!