天天看點

電商項目後端架構SpringBoot、MybatisPlus

後端架構基礎

1.代碼自動生成工具 mybatis-plus

(1)首先需要添加依賴檔案

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>

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

        <!-- 代碼自動生成工具 mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>

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

        <!-- spring-boot-devtools -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <!-- json object對象支援 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>

        <!-- 代碼生成器中使用freemarker -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
            <version>2.2.2.RELEASE</version>
        </dependency>

           

(2)設定application.yml檔案中資料庫資訊并且建立資料庫及表

server:
  port: 8080

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/market?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: 123456
    druid:
      validation-query: SELECT 1 FROM DUAL
      initial-size: 10 #初始化時建立實體連接配接的個數。
      min-idle: 10 #最小連接配接池數量
      max-active: 200 #最大連接配接池數量
      min-evictable-idle-time-millis: 300000 #連接配接保持空閑而不被驅逐的最小時間
      test-on-borrow: false #申請連接配接時執行validationQuery檢測連接配接是否有效
      test-while-idle: true #申請連接配接的時候檢測,如果空閑時間大于timeBetweenEvictionRunsMillis,
      #執行validationQuery檢測連接配接是否有效。
      time-between-eviction-runs-millis: 30000 #1) Destroy線程會檢測連接配接的間隔時間,
      #如果連接配接空閑時間大于等于minEvictableIdleTimeMillis則關閉實體連接配接。
      #2) testWhileIdle的判斷依據
      pool-prepared-statements: true #是否緩存preparedStatement,也就是PSCache
      max-open-prepared-statements: 100 #要啟用PSCache,必須配置大于0,當大于0時,
      #poolPreparedStatements自動觸發修改為true

mybatis-plus:
  type-aliases-package: com.example.entity
  global-config:
    db-config:
      logic-delete-field: deleted
      logic-delete-value: 1
      logic-not-delete-value: 0
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    map-underscore-to-camel-case: true
    cache-enabled: false
    jdbc-type-for-null: 'null'
           

(3)自動生成代碼文檔代碼

注意更改相應父類位置以及資料庫資訊、表資訊

package com.imooc.mall.common;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
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 java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

// 示範例子,執行 main 方法控制台輸入子產品表名回車自動生成對應項目目錄中
public class CodeGenerator {

    /**
     * <p>
     * 讀取控制台内容
     * </p>
     */
    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.isNotBlank(ipt)) {
                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("pommy");
        gc.setOpen(false);
        // gc.setSwagger2(true); 實體屬性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 資料源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mall?useUnicode=true&useSSL=false&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        dsc.setDbType(DbType.MYSQL);
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        //pc.setModuleName(scanner("子產品名"));
        pc.setParent("com.imooc.mall");
        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";

        // 自定義輸出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定義配置會被優先輸出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定義輸出檔案名 , 如果你 Entity 設定了前字尾、此處注意 xml 的名稱會跟着發生變化!!
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判斷自定義檔案夾是否需要建立
                checkDir("調用預設方法建立的目錄,自定義目錄用");
                if (fileType == FileType.MAPPER) {
                    // 已經生成 mapper 檔案判斷存在,不想重新生成傳回 false
                    return !new File(filePath).exists();
                }
                // 允許生成模闆檔案
                return true;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

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

        // 配置自定義輸出模闆
        //指定自定義模闆路徑,注意不要帶上.ftl/.vm, 會根據使用的模闆引擎自動識别
        // templateConfig.setEntity("templates/entity2.java");
        // 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("你自己的父類實體,沒有就不用設定!");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setLogicDeleteFieldName("deleted");  //設定邏輯删除字段名
        // 公共父類
        //strategy.setSuperControllerClass("你自己的父類控制器,沒有就不用設定!");
        // 寫于父類中的公共字段
        //strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多個英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix("imooc_mall_");

        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

           

(4)持久層注入

在主類上方添加:@MapperScan(“com.example.mapper”)

2.分頁功能

需要添加MybatisConfiguration配置檔案完成分頁

@Configuration
@MapperScan("com.example.mapper")
public class MyBatisConfiguration {
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }
}
           

具體使用的時候用Page即可

3. 邏輯删除deleted屬性位置(1為删除)

(1)首先在application.yml中添加以下内容

mybatis-plus:
  type-aliases-package: com.example.entity
  global-config:
    db-config:
      logic-delete-field: deleted
      logic-delete-value: 1
      logic-not-delete-value: 0
           

(2)然後在entity實體類中的deleted屬性前加上@TableLogic,表示邏輯删除屬性

電商項目後端架構SpringBoot、MybatisPlus

4. 模拟支付----支付寶沙箱環境設定

(1)登入客支付寶戶端賬号,開啟公鑰

前端基礎知識Vue

注意跨域通路時,即在浏覽器中輸入網址通路資料,需要用主機ip位址,而不是localhost,之後在controller上面添加解決跨域通路的注解@CrossOrigin

在CMD中用ipconfig去檢視本地的ip位址,ip4:10.6.12.170

電商項目後端架構SpringBoot、MybatisPlus

1. vue cli建立新項目

下載下傳anxios時,項目有中文路徑往往不成功,此時可以選擇别的方式,在cmd中切換到該路徑下然後進行npm install axios,即可成功