SpringBoot + Vue前后端分离项目实战 || 二:Spring Boot后端与数据库连接

系列文章:
SpringBoot + Vue前后端分离项目实战 || 一:Vue前端设计

文章目录

    • 新建Spring后台项目
      • 添加依赖
    • 新建数据库
    • IDEA 连接数据库
    • IDEA 自动创建类实体
    • 定义数据传递至前端的格式

B站视频讲解:2023全网最简单但实用的SpringBoot+Vue前后端分离项目实战

不想看视频可浏览此文章笔记,比较详细

新建Spring后台项目

IDEA 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>

    </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','super@aliyun.com','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','zhangsan@gmail.com','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','lisi@gmail.com','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','wangwu@gmail.com','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','zhaoer@gmail.com','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','songliu@gmail.com','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来自动创建类实体的java代码
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下新建一个package: common 然后新建package: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 显示数据则成功
    在这里插入图片描述
    此处数据格式也与前端对接得上

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/30487.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

RTC

文章目录 前言驱动应用程序运行 前言 RTC&#xff08;Real Time Clock&#xff0c;实时时钟&#xff09;是个常用的外设&#xff0c;通过 RTC 我们可以知道日期和时间信息&#xff0c;因此在需要记录时间的场合就需要实时时钟。 可以使用专用的实时时钟芯片来完成此功能&#…

扫雷小游戏【C语言】

目录 前言 一、基本实现逻辑 二、实现步骤 1. 我们希望在进入游戏时有一个菜单让我们选择 2. 我们希望可以重复的玩&#xff08;一把玩完了还可以接着玩&#xff09; 3. 采用多文件形式编程 4.要扫雷先得有棋盘&#xff08;创建棋盘R*N&#xff09; 5.初始化棋盘 6.打…

【网络安全】深入解析 PHP 代码审计技术与实战

前言 登录某个网站并浏览其页面时&#xff0c;注意到了一些看起来不太对劲的地方。这些迹象可能是该网站存在漏洞或被黑客入侵的标志。为了确保这个网站的安全性&#xff0c;需要进行代码审计&#xff0c;这是一项专门针对软件代码进行检查和分析的技术。在本文中&#xff0c;…

一、Docker介绍

学习参考&#xff1a;尚硅谷Docker实战教程、Docker官网、其他优秀博客(参考过的在文章最后列出) 目录 前言一、Docker是什么&#xff1f;二、Docker能干撒&#xff1f;三、容器虚拟化技术 和 虚拟机有啥区别&#xff1f;1.虚拟机2.容器虚拟化技术3.对比4.Docker为啥比VM虚拟机…

献给蓝初小白系列(二)——Liunx应急响应

1、Linux被入侵的症状​​ ​​https://blog.csdn.net/weixin_52351575/article/details/131221720​​ 2、Linux应急措施 顺序是&#xff1a;隔离主机--->阻断通信--->清除病毒--->可疑用户--->启动项和服务--->文件与后门--->杀毒、重装系统、恢复数据 …

AAC ADTS格式分析

标题 1.AAC简介2. AAC ADTS格式分析2.1 adts_fixed_header详细介绍2.2 adts_variable_header详细介绍 1.AAC简介 AAC音频格式:Advanced Audio Coding(⾼级⾳频解码)&#xff0c;是⼀种由MPEG-4标准定义的有损⾳频压缩格式&#xff0c;由Fraunhofer发展&#xff0c;Dolby, Sony…

vue3 + TS + elementplus + pinia实现后台管理系统左侧菜单联动实现 tab根据路由切换联动内容

效果图&#xff1a; home.vue页面代码 <template><el-container><el-aside width"collapse ? 200px : 70px"><el-button color"#626aef" click"collapseToggle()"><el-icon><Expand v-if"collapse"…

SQL Server 数据加密功能解析

数据加密是数据库被破解、物理介质被盗、备份被窃取的最后一道防线&#xff0c;数据加密&#xff0c;一方面解决数据被窃取安全问题&#xff0c;另一方面有关法律要求强制加密数据。SQL Server的数据加密相较于其他数据库&#xff0c;功能相对完善&#xff0c;加密方法较多。通…

Unity Class深拷贝问题分析

Unity Class深拷贝问题分析 前言常用解决方案1.手动复制字段2.使用序列化工具3.使用Instantiate方法(只能用于MonoBehaviour)4.重写运算符赋值5.使用Visual Scripting中提供的拷贝函数&#xff08;推荐&#xff09; 前言 在Unity项目中&#xff0c;我们面临一个读取数据表并深…

web前端-TypeScript学习

web前端-TypeScript学习 TypeScript 介绍TypeScript 初体验安装编译TS的工具包编译并运行TS代码 TypeScript 常用类型类型注解常用基础类型原始类型数组类型类型别名函数类型对象类型接口元祖类型推论类型断言字面量类型枚举any类型typedof TypeScript 高级类型class类class的基…

笔记:WebRTC 网络技术理论与实战(二)

WebRTC技术笔记 笔记&#xff1a;WebRTC 网络技术理论与实战&#xff08;一&#xff09; 作者&#xff1a;李俊才 &#xff08;jcLee95&#xff09;&#xff1a;https://blog.csdn.net/qq_28550263 邮箱 &#xff1a;291148484163.com 本文地址&#xff1a;https://blog.csdn.n…

C语言之文件的读写(1)

前面三部分已经给大家介绍过了&#xff0c;网址发给大家方便大家复习 打开方式如下&#xff1a; 文件使用方式 含义 如果指定文件不存在 “r”&#xff08;只读&#xff09; 为了输入数据&#xff0c;打开一个已经存在的文本文件 出错 “w”&#xff08;只写&#xff09; 为了输…

OC(iOS)中常见的面试题汇整(大全)

你如何理解OC这门语言的?谈一下你对OC的理解? ​​​​​​​ OC语言是C语言的一个超集,只是在C语言的基础上加上了面向对象的语言特征,如:继承,封装,多态. 封装:把属性和方法封装成一个类,方便我们使用 多态:不同对象对于同一消息的不同响应,子类可以重…

同时安装vue-cli2和vue-cli3

同时安装vue-cli2和vue-cli3 发布时间环境安装后的效果安装vue-cli2安装vue-cli3vue-cli3和vue-cli2的区别vue-cli2目录结构vue-cli3目录结构 发布时间 vue版本发布时间Seed.js2013年vue最早版本最初命名为Seedvue-js 0.62013年12月更名为vuevue-js 0.82014年1月对外发布vue-j…

微软ChatGPT技术的底层支撑——GPU

我是荔园微风&#xff0c;作为一名在IT界整整25年的老兵&#xff0c;今天我们来看一看微软ChatGPT技术的底层支撑——GPU。 想要了解GPU&#xff0c;你必须要清楚CPU、GPU、TPU三者的关系。 微软的chatgpt是基于复杂的人工神经网络和强化学习的技术&#xff0c;这是如何运算的…

io.netty学习(八)零拷贝原理

目录 零拷贝 传统I/O操作存在的性能问题 零拷贝技术原理 虚拟内存 mmap/write 方式 sendfile 方式 带有 scatter/gather 的 sendfile方式 splice 方式 总结 io.netty学习使用汇总 零拷贝 零拷贝&#xff08;Zero-Copy&#xff09;是一种 I/O 操作优化技术&#xff0c…

web漏洞-反序列化之PHPJAVA全解(上)(37)

这个很重要 为什么会产生这个东西&#xff1a;序列化之后便于我们对象的传输和保存&#xff0c;这个作用就是为了数据的传递和格式的转换&#xff0c;我们称之为序列化。 在这给过程中&#xff0c;会涉及到一种叫做有类和无类的情况&#xff0c;开发里面经常看到的一个东西&a…

AbstractQueuedSynchronizer源码

介绍 基于队列的抽象同步器&#xff0c;它是jdk中所有显示的线程同步工具的基础&#xff0c;像ReentrantLock/DelayQueue/CountdownLatch等等&#xff0c;都是借助AQS实现的。 public abstract class AbstractQueuedSynchronizerextends AbstractOwnableSynchronizerimplemen…

使用omp并行技术加速最短路径算法-迪杰斯特拉(Dijkstra)算法(记录最短路径和距离)

原理&#xff1a; Dijkstra算法是解决**单源最短路径**问题的**贪心算法** 它先求出长度最短的一条路径&#xff0c;再参照该最短路径求出长度次短的一条路径 直到求出从源点到其他各个顶点的最短路径。 首先假定源点为u&#xff0c;顶点集合V被划分为两部分&#xff1a;集合…

【玩转Linux操作】Linux服务管理

&#x1f38a;专栏【玩转Linux操作】 &#x1f354;喜欢的诗句&#xff1a;更喜岷山千里雪 三军过后尽开颜。 &#x1f386;音乐分享【如愿】 大一同学小吉&#xff0c;欢迎并且感谢大家指出我的问题&#x1f970; 文章目录 &#x1f354;服务(service)管理⭐service管理指令 &…