SpringBoot + Vue フロントエンドとバックエンド分離プロジェクトの実戦 || 2: Spring Boot バックエンドとデータベース接続

一連の記事:
SpringBoot + Vue フロントエンドとバックエンドの分離プロジェクトの実践 || 1 つ: Vue フロントエンド設計
SpringBoot + Vue フロントエンドとフロントエンドの分離プロジェクトの実践 || 2 つ: Spring Boot バックエンドとデータベース接続
SpringBoot + Vue フロントエンドとフロントエンド分離プロジェクトの実践 || 3: Spring Boot バックエンドと Vue フロントエンド接続
SpringBoot + Vue フロントエンドとバックエンド分離プロジェクトの実践 || 4: ユーザー管理機能実装
SpringBoot + Vue フロントエンド分離プロジェクト実践 || 5: ユーザー管理機能フォローアップ

Bilibili のビデオ説明: 2023 年の最もシンプルだが実用的な SpringBoot+Vue フロントエンドとバックエンドの分離プロジェクト。

ビデオを見たくない場合は、この記事のメモを参照して詳細を確認してください。

新しい Spring バックエンド プロジェクトを作成する

アイデアfile->new->project
ここに画像の説明を挿入します

選ぶSpring Initializr
ここに画像の説明を挿入します

ここには直接的な依存関係はありませんFINISH
ここに画像の説明を挿入します

依存関係を追加する

まず、ローカルmaven構成が構成されていることを確認し、File -> Settings「Maven の表示」をクリックします。
ここに画像の説明を挿入します
ここに画像の説明を挿入します
ここに画像の説明を挿入します

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.7.8</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ums</groupId>
    <artifactId>x-admin</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>x-admin</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.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>

        <!-- web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
        </dependency>
        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!-- freemarker -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>

        <!-- fastjson -->
        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>2.0.7</version>
        </dependency>

    </dependencies>

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

</project>

ヒットした場合は、右側のMaven中央の刷新ボタンをクリックし、IDEA が依存関係をダウンロードするまで待ちます。さらに数回更新して待ちます。
ここに画像の説明を挿入します

新しいデータベースを作成する

navicatローカルデータベースにリンクして新しいデータベースを作成するxdb
ここに画像の説明を挿入します

新しい123.txtドキュメントを作成し、次の SQL コマンドをコピーして名前を変更します。123.sql

CREATE TABLE `x_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `password` varchar(100) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `phone` varchar(20) DEFAULT NULL,
  `status` int(1) DEFAULT NULL,
  `avatar` varchar(200) DEFAULT NULL,
   `deleted` INT(1) DEFAULT 0,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

insert into `x_user` (`id`, `username`, `password`, `email`, `phone`, `status`, `avatar`, `deleted`) values('1','admin','123456','[email protected]','18677778888','1','https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif','0');
insert into `x_user` (`id`, `username`, `password`, `email`, `phone`, `status`, `avatar`, `deleted`) values('2','zhangsan','123456','[email protected]','13966667777','1','https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif','0');
insert into `x_user` (`id`, `username`, `password`, `email`, `phone`, `status`, `avatar`, `deleted`) values('3','lisi','123456','[email protected]','13966667778','1','https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif','0');
insert into `x_user` (`id`, `username`, `password`, `email`, `phone`, `status`, `avatar`, `deleted`) values('4','wangwu','123456','[email protected]','13966667772','1','https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif','0');
insert into `x_user` (`id`, `username`, `password`, `email`, `phone`, `status`, `avatar`, `deleted`) values('5','zhaoer','123456','[email protected]','13966667776','1','https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif','0');
insert into `x_user` (`id`, `username`, `password`, `email`, `phone`, `status`, `avatar`, `deleted`) values('6','songliu','123456','[email protected]','13966667771','1','https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif','0');

CREATE TABLE `x_role` (
  `role_id` int(11) NOT NULL AUTO_INCREMENT,
  `role_name` varchar(50) DEFAULT NULL,
  `role_desc` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`role_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;

insert into `x_role` (`role_id`, `role_name`, `role_desc`) values('1','admin','超级管理员');
insert into `x_role` (`role_id`, `role_name`, `role_desc`) values('2','hr','人事专员');
insert into `x_role` (`role_id`, `role_name`, `role_desc`) values('3','normal','普通员工');

CREATE TABLE `x_menu` (
  `menu_id` int(11) NOT NULL AUTO_INCREMENT,
  `component` varchar(100) DEFAULT NULL,
  `path` varchar(100) DEFAULT NULL,
  `redirect` varchar(100) DEFAULT NULL,
  `name` varchar(100) DEFAULT NULL,
  `title` varchar(100) DEFAULT NULL,
  `icon` varchar(100) DEFAULT NULL,
  `parent_id` int(11) DEFAULT NULL,
  `is_leaf` varchar(1) DEFAULT NULL,
  `hidden` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`menu_id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4;

insert  into `x_menu`(`menu_id`,`component`,`path`,`redirect`,`name`,`title`,`icon`,`parent_id`,`is_leaf`,`hidden`) values (1,'Layout','/user','/user/list','userManage','用户管理','userManage',0,'N',0),(2,'user/user','list',NULL,'userList','用户列表','userList',1,'Y',0),(3,'user/role','role',NULL,'roleList','角色列表','role',1,'Y',0),(4,'user/permission','permission',NULL,'permissionList','权限列表','permission',1,'Y',0);

CREATE TABLE `x_user_role` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) DEFAULT NULL,
  `role_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;

insert into `x_user_role` (`id`, `user_id`, `role_id`) values('1','1','1');

CREATE TABLE `x_role_menu` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `role_id` int(11) DEFAULT NULL,
  `menu_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;

右クリックしxdbて選択します运行SQL文件
ここに画像の説明を挿入します

ファイルを見つけて123.sqlから実行する
ここに画像の説明を挿入します

正常に実行されました
ここに画像の説明を挿入します

IDEA がデータベースに接続します

を開き、そのようなファイルがなく、ファイルsrc\main\resources\application.ymlのみがある場合は、そのサフィックスを直接次のように変更します。application.property.yml
ここに画像の説明を挿入します

コードを書く

server:
  port: 9999            # 端口号
spring:
  datasource:
    username: root      # 数据库名
    password: 1234      # 数据库密码
    url: jdbc:mysql:///xdb

  redis:
    port: 6379
    host: localhost

logging:
  level:
    com.ums: debug

IDEA はクラス エンティティを自動的に作成します

まず新しいpackage:sys空のパッケージを作成すると、生成されたコードがここに配置されます
ここに画像の説明を挿入します

Mybatis-plusクラス エンティティを自動的に作成するために使用される
以下にsrc\test新しいエンティティを作成しますjava类:CodeGenerator
ここに画像の説明を挿入します

次に、次のコードを記述します。コードには説明があります。

package com.ums;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.Collections;

public class CodeGenerator {
    
    
    public static void main(String[] args) {
    
    
        String url = "jdbc:mysql:///xdb";       // 与配置文件 一致
        String username = "root";
        String password = "1234";
        String author = "anthony";
        String moduleName = "sys";              // 系统管理的代码包
        String mapperLocation = "D:\\VueProj\\x-admin\\src\\main\\resources\\mapper\\" + moduleName ;
        String tables = "x_menu,x_role,x_role_menu,x_user,x_user_role";     // 与数据库中的表名一致,逗号隔开

        FastAutoGenerator.create(url, username, password)
            .globalConfig(builder -> {
    
    
                builder.author(author) // 设置作者
//                        .enableSwagger() // 开启 swagger 模式
//                        .fileOverride() // 覆盖已生成文件
                        .outputDir("D:\\VueProj\\x-admin\\src\\main\\java"); // 指定输出目录
            })

            .packageConfig(builder -> {
    
    
                builder.parent("com.ums") // 设置父包名
                        .moduleName(moduleName) // 设置父包模块名
                        .pathInfo(Collections.singletonMap(OutputFile.xml, mapperLocation)); // 设置mapperXml生成路径
            })
            .strategyConfig(builder -> {
    
    
                builder.addInclude(tables) // 设置需要生成的表名
                        .addTablePrefix("x_"); // 设置过滤表前缀, x_menu 生成的类实体无 x_ 前缀
            })
            .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
            .execute();
    }
}

クリックrun
ここに画像の説明を挿入します

コードを生成する
ここに画像の説明を挿入します

フロントエンドに渡されるデータの形式を定義する

前のセクションで説明したように、フロントエンド ログインの応答データ形式を記録する必要があるため
、バックエンドがこの形式を構築します。

{
    
    "code":20000,"data":{
    
    "token":"admin-token"}}

以下のsrc\main新しいパッケージを作成します。common次に、新しいパッケージを作成します。vo次に、新しい Java クラスを作成します。Result
ここに画像の説明を挿入します

コメントと説明を含むコードを作成する

package com.ums.common.vo;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> {
    
    
    private Integer code;       // 成功失败的代码,此处定义2000为成功,2001为失败
    private String message;     // 消息,里面包含数据data
    private T data;             // 未定义的数据形式

    // 此处重载了四个 success 方法,有些能够返回数据,有的只返回代码或信息
    public static <T> Result<T> success() {
    
    
        return new Result<>(20000,"success",null);
    }

    public static <T> Result<T> success(T data) {
    
    
        return new Result<>(20000,"success",data);
    }

    public static <T> Result<T> success(T data, String message) {
    
    
        return new Result<>(20000,message,data);
    }

    public static <T> Result<T> success(String message) {
    
    
        return new Result<>(20000,message,null);
    }

    public static<T>  Result<T> fail(){
    
    
        return new Result<>(20001,"fail",null);
    }

    public static<T>  Result<T> fail(Integer code){
    
    
        return new Result<>(code,"fail",null);
    }

    public static<T>  Result<T> fail(Integer code, String message){
    
    
        return new Result<>(code,message,null);
    }

    public static<T>  Result<T> fail( String message){
    
    
        return new Result<>(20001,message,null);
    }
}

テスト

  1. まずsrc\main\javaメインプログラムXAdminApplicationにコメントを追加します@MapperScan("com.ums.*.mapper")
    ここに画像の説明を挿入します
  2. UserControllerテストコードを書くために入力してください
    ここに画像の説明を挿入します
    package com.ums.sys.controller;
    
    import com.ums.common.vo.Result;
    import com.ums.sys.entity.User;
    import com.ums.sys.service.IUserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.List;
    
    /**
     * <p>
     *  前端控制器
     * </p>
     *
     * @author anthony
     * @since 2023-06-16
     */
    @RestController
    @RequestMapping("/user")
    public class UserController {
          
          
        @Autowired
        private IUserService userService;
    
        @GetMapping("/all")
        public Result<List<User>> getAllUser() {
          
          
            List<User> list = userService.list();
            return Result.success(list,"查询成功");
        }
    }
    
  3. メインプログラムを実行し、
    ここに画像の説明を挿入します
    ブラウザに入り、http://localhost:9999/user/allデータを入力し、正常に表示します。
    ここに画像の説明を挿入します
    ここでのデータ形式はフロントエンドにも接続できます。

おすすめ

転載: blog.csdn.net/qq_56039091/article/details/131306802