第一个搭建SpringBoot项目(连接mysql)
首先新建项目找到Spring Initializr 我使用的URL是https://start.spring.io这里最低的JDK版本是17,而且当网速不好的时候可能会显示超时,这里可以选用阿里云的镜像https://start.aliyun.com可以更快一些但是里面还是有一些区别的
我们这里选择Java语言,Maven框架
在这里我们选择一些我们需要用到的
这个版本可以选低一点更加稳定
进来之后我们需要先等pom文件加载,我们可以选择刷新Maven
加载完之后由于我们加载了MySQL所以还不能运行可以先注释掉,然后刷新maven
后面就可以运行了,但是它默认的是8080端口,有可能会有被占用的我们可以更改端口
后面既可以运行了
运行结果就是这样的后面没有了,刚开始由于我学习的时候和别人运行的不一样,还以为是卡住了,调试了好久好久,结果发现这就已经是运行了
下面我们就可以去页面看看结果了
用阿里云镜像的输出会有点不一样但是没有问题。
下面我们就可以创建一个测试类
新建一个TestController
@RestController
public class TestController {@GetMapping("/hello")public String hello(){return "hello word!";}
}
再去页面观察
rest api规范
路径
路径又称"终点"(endpoint),表示API的具体网址。在RESTfuI架构中,每个网址代表一种资源(resource),所以网址中不能有动词,只能有名词,而且所用的名词往往与数据库的表格名对应。
Http 动词
GET(SELECT):从服务器取出资源(一项或多项)。
POST(CREATE):在服务器新建一个资源。
PUT(UPDATE):在服务器更新资源(客户端提供改变后的完整资源)。。PATCH(UPDATE):在服务器更新资源(客户端提供改变的属性)
DELETE(DELETE):从服务器删除资源。
新建一个数据库,创建表student
使用mysql语句是这样的
创建
在这里我遇到的问题是JpaRepository我继承不了,然后不断的查找问题是更改pom文件里面的内容
加入
org.springframework.data
spring-data-jpa
然后刷新一下maven就好了
创建Student
Student
package com.example.mysqldemo3.dao;import jakarta.persistence.*;import static jakarta.persistence.GenerationType.IDENTITY;@Entity
@Table(name = "student")
public class Student {@Id@Column(name = "id")@GeneratedValue(strategy = IDENTITY)private long id;@Column(name = "name")private String name;@Column(name = "email")private String email;@Column(name = "age")private int age;public long getId() {return id;}public void setId(long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}
}
返回到接口补全代码
package com.example.mysqldemo3.dao;import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;@Repository
public interface StudentRepository extends JpaRepository<Student,Long> {}
Service层
StudentService
package com.example.mysqldemo3.service;import com.example.mysqldemo3.dao.Student;public interface StudentService {Student getStudentById(long id);}
StudentServiceImpl
package com.example.mysqldemo3.service;import com.example.mysqldemo3.dao.Student;
import com.example.mysqldemo3.dao.StudentRepository;
import jakarta.persistence.Id;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class StudentServiceImpl implements StudentService{@Autowiredprivate StudentRepository StudentRepository;@Overridepublic Student getStudentById(long id) {return StudentRepository.findById(id).orElseThrow(RuntimeException::new) ;}
}
controller层
package com.example.mysqldemo3.controller;import com.example.mysqldemo3.dao.Student;
import com.example.mysqldemo3.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;@RestController
public class StudentController {@Autowiredprivate StudentService studentService;@GetMapping("/student/{id}")public Student getStudentById(@PathVariable long id){return studentService.getStudentById(id);}
}
连接数据库这些配置写在application里面
数据库
spring.application.name=mysql-demo3
server.port=8085
spring.datasource.url=jdbc:mysql://localhost:3306/数据库名字?characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=sgz250hhh
在数据库中填入数据
后面就可以去网页测试了
再往后我们需要做一些信息的隐藏,不想去展示这莫多的数据
创建
StudentDTO进行封装
package com.example.mysqldemo3.dto;public class StudentDTO {private long id;private String name;private String email;public long getId() {return id;}public void setId(long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}
}
新建converter将student的数据进行转换成DTO
StudentConverter
package com.example.mysqldemo3.converter;import com.example.mysqldemo3.dao.Student;
import com.example.mysqldemo3.dto.StudentDTO;public class StudentConverter {public static StudentDTO converStudent(Student student){//student转换成DTO对象StudentDTO studentDTO = new StudentDTO();studentDTO.setId(student.getId());studentDTO.setName(student.getName());studentDTO.setEmail(student.getEmail());return studentDTO;}
}
新建
判断是否查询成功
Response
package com.example.mysqldemo3;public class Response <T>{//返回后端的一些格式private T data;private boolean success;private String errorMsg;public static <K> Response<K> newSuccess(K data){//返回成功Response<K> response = new Response<>();response.setData(data);response.setSuccess(true);return response;}public static Response<Void> newFail(String errorMsg){//返回失败Response<Void> response = new Response<>();response.setErrorMsg(errorMsg);response.setSuccess(false);return response;}public T getData() {return data;}public void setData(T data) {this.data = data;}public boolean isSuccess() {return success;}public void setSuccess(boolean success) {this.success = success;}public String getErrorMsg() {return errorMsg;}public void setErrorMsg(String errorMsg) {this.errorMsg = errorMsg;}
}
StudentService
package com.example.mysqldemo3.service;import com.example.mysqldemo3.dao.Student;
import com.example.mysqldemo3.dto.StudentDTO;public interface StudentService {StudentDTO getStudentById(long id);}
StudentServiceImpl
package com.example.mysqldemo3.service;import com.example.mysqldemo3.converter.StudentConverter;
import com.example.mysqldemo3.dao.Student;
import com.example.mysqldemo3.dao.StudentRepository;
import com.example.mysqldemo3.dto.StudentDTO;
import jakarta.persistence.Id;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class StudentServiceImpl implements StudentService{@Autowiredprivate StudentRepository StudentRepository;@Overridepublic StudentDTO getStudentById(long id) {Student student = StudentRepository.findById(id).orElseThrow(RuntimeException::new);return StudentConverter.converStudent(student);}
}
StudentController
package com.example.mysqldemo3.controller;import com.example.mysqldemo3.Response;
import com.example.mysqldemo3.dao.Student;
import com.example.mysqldemo3.dto.StudentDTO;
import com.example.mysqldemo3.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;@RestController
public class StudentController {@Autowiredprivate StudentService studentService;@GetMapping("/student/{id}")public Response<StudentDTO> getStudentById(@PathVariable long id){return Response.newSuccess(studentService.getStudentById(id));}
}
刷新页面
就可以看见age被隐藏起来了
后面的就是增加删除和修改的操作可以使用Postman进行接口测试,可以直接官网下载
StudentServiceImpl
package com.example.mysqldemo3.service;import com.example.mysqldemo3.converter.StudentConverter;
import com.example.mysqldemo3.dao.Student;
import com.example.mysqldemo3.dao.StudentRepository;
import com.example.mysqldemo3.dto.StudentDTO;
import jakarta.persistence.Id;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;import java.util.List;@Service
public class StudentServiceImpl implements StudentService{@Autowiredprivate StudentRepository StudentRepository;@Overridepublic StudentDTO getStudentById(long id) {Student student = StudentRepository.findById(id).orElseThrow(RuntimeException::new);return StudentConverter.converStudent(student);}@Overridepublic Long addNewStudent(StudentDTO studentDTO) {List<Student> studentList = StudentRepository.findByEmail(studentDTO.getEmail());if (!CollectionUtils.isEmpty(studentList)){throw new IllegalStateException("email:"+studentDTO.getEmail()+"has been taken");}Student student = StudentRepository.save(StudentConverter.converStudent(studentDTO));return student.getId();}@Overridepublic void deleteStudentById(long id) {StudentRepository.findById(id).orElseThrow(()->new IllegalArgumentException("id"+id+"doesn`s exist!"));StudentRepository.deleteById(id);}@Overridepublic StudentDTO updateStudentById(long id, String name, String email) {Student studentDB = StudentRepository.findById(id).orElseThrow(()->new IllegalArgumentException("id"+id+"doesn`s exist!"));if (StringUtils.hasLength(name) && !studentDB.getName().equals(name)){studentDB.setName(name);}if(StringUtils.hasLength(email) && !studentDB.getEmail().equals(email)){studentDB.setEmail(email);}Student student = StudentRepository.save(studentDB);return StudentConverter.converStudent(student);}}
StudentService
package com.example.mysqldemo3.service;import com.example.mysqldemo3.dao.Student;
import com.example.mysqldemo3.dto.StudentDTO;public interface StudentService {StudentDTO getStudentById(long id);Long addNewStudent(StudentDTO studentDTO);void deleteStudentById(long id);StudentDTO updateStudentById(long id, String name, String email);
}
StudentRepository
package com.example.mysqldemo3.dao;import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;import java.util.List;@Repository
public interface StudentRepository extends JpaRepository<Student,Long> {List<Student> findByEmail(String emile);}
StudentConverter
package com.example.mysqldemo3.converter;import com.example.mysqldemo3.dao.Student;
import com.example.mysqldemo3.dto.StudentDTO;public class StudentConverter {public static StudentDTO converStudent(Student student){//student转换成DTO对象StudentDTO studentDTO = new StudentDTO();studentDTO.setId(student.getId());studentDTO.setName(student.getName());studentDTO.setEmail(student.getEmail());return studentDTO;}public static Student converStudent(StudentDTO StudentDTO){//student转换成DTO对象Student student = new Student();student.setName(StudentDTO.getName());student.setEmail(StudentDTO.getEmail());return student;}
}
StudentController
package com.example.mysqldemo3.controller;import com.example.mysqldemo3.Response;
import com.example.mysqldemo3.dao.Student;
import com.example.mysqldemo3.dto.StudentDTO;
import com.example.mysqldemo3.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;@RestController
public class StudentController {@Autowiredprivate StudentService studentService;@GetMapping("/student/{id}")public Response<StudentDTO> getStudentById(@PathVariable long id){return Response.newSuccess(studentService.getStudentById(id));}@PostMapping("/student")public Response<Long> addNewStudent(@RequestBody StudentDTO studentDTO){return Response.newSuccess(studentService.addNewStudent(studentDTO));}@DeleteMapping("/student/{id}")public void deleteStudentById(@PathVariable long id){studentService.deleteStudentById(id);}@PutMapping("/student/{id}")public Response<StudentDTO> updateStudentById(@PathVariable long id,@RequestParam(required = false) String name,@RequestParam(required = false) String email){return Response.newSuccess(studentService.updateStudentById(id,name,email));}
}
最后就可以使用maven对文件进行打包了
相关文章:

第一个搭建SpringBoot项目(连接mysql)
首先新建项目找到Spring Initializr 我使用的URL是https://start.spring.io这里最低的JDK版本是17,而且当网速不好的时候可能会显示超时,这里可以选用阿里云的镜像https://start.aliyun.com可以更快一些但是里面还是有一些区别的 我们这里选择Java语言&a…...

docker部署rabbitMQ 单机版
获取rabbit镜像:我们选择带有“mangement”的版本(包含web管理页面); docker pull rabbitmq:management 创建并运行容器: docker run -d --name rabbitmq -p 5677:5672 -p 15677:15672 rabbitmq:management --name:…...

PDF 全文多语言 AI 摘要 API 数据接口
PDF 全文多语言 AI 摘要 API 数据接口 PDF / 文本摘要 AI 生成 PDF 文档摘要 AI 处理 / 智能摘要。 1. 产品功能 支持多语言摘要生成;支持 formdata 格式 PDF 文件流传参;快速处理大文件;基于 AI 模型,持续迭代优化;…...

《信息系统安全》课程实验指导
第1关:实验一:古典密码算法---代换技术 任务描述 本关任务:了解古典密码体制技术中的代换技术,并编程实现代换密码的加解密功能。 注意所有明文字符为26个小写字母,也就是说字母表为26个小写字母。 相关知识 为了完…...

Accelerated Soft Error Testing 介绍
加速软错误测试(Accelerated Soft Error Testing, ASET)是一种评估半导体器件或集成电路(ICs)在高辐射环境中发生软错误率(Soft Error Rate, SER)的方法。这种测试方法通过模拟或加速软错误的发生,以便在较短时间内评估器件的可靠性。软错误指的是那些不会对硬件本身造成…...

Redis缓存常用的读写策略
缓存常用的读写策略 缓存与DB的数据不一致问题,大多数都是指DB的数据已经修改,而缓存中的数据还是旧数据的情况。 旁路缓存模式 对于读操作:基本上所有模式都是先尝试从缓存中读,没有的话再去DB读取,然后写到缓存中…...

9月产品更新 | 超10项功能升级,快来看看你的需求上线了吗?
Smartbi用户可以在官网(PC端下载),更新后便可以使用相关功能,也可以在官网体验中心体验相关功能。 接下来,我们一起来看看都有哪些亮点功能更新吧。 ▎插件商城 Smartbi麦粉社区的应用市场新增了“插件”模块…...

ARP协议工作原理析解 (详细抓包分析过程)
目录 1. ARP 协议 2. 工作原理 3. ARP 协议报文格式 4. ARP 缓存的查看和修改 5. tcpdump 抓包分析 ARP 协议工作原理 5.1 搭建 2 台虚拟机 5.2 在主机 192.168.0.155 打开一个shell命令行开启抓包监听 5.3 在主机 192.168.0.155 打开另一个shell命令行 telnet 192.168.…...

axure动态面板
最近转管理岗了,作为项目负责人,需要常常与客户交流沟通,这时候画原型的能力就是不可或缺的本领之一了,关于axure可能很多it行业者都不是很陌生,简单的功能呢大家就自行去摸索,我们这次从动态面板开始讲起。…...

[论文笔记]Making Large Language Models A Better Foundation For Dense Retrieval
引言 今天带来北京智源研究院(BAAI)团队带来的一篇关于如何微调LLM变成密集检索器的论文笔记——Making Large Language Models A Better Foundation For Dense Retrieval。 为了简单,下文中以翻译的口吻记录,比如替换"作者"为"我们&quo…...

Linux平台屏幕|摄像头采集并实现RTMP推送两种技术方案探究
技术背景 随着国产化操作系统的推进,市场对国产化操作系统下的生态构建,需求越来越迫切,特别是音视频这块,今天我们讨论的是如何在linux平台实现屏幕|摄像头采集,并推送至RTMP服务。 我们知道,Linux平台&…...

梧桐数据库|中秋节活动·抽奖领取大闸蟹
有话说 众所周不知,我的工作就是做一个国产的数据库产品—中国移动梧桐数据库(简称WuTongDB)。 近期我们举办了一次小活动,来提升梧桐数据库的搜索量和知名度,欢迎大家来参加,免费抽奖领取大闸蟹哦~~~ 具…...

Python怎么发送邮件:基础步骤与详细教程?
Python怎么发送邮件带附件?怎么使用Python发送邮件? 无论是工作中的通知、报告,还是生活中的问候、邀请,电子邮件都扮演着不可或缺的角色。那么,Python怎么发送邮件呢?AokSend将详细介绍Python发送邮件的基…...

[译] 大模型推理的极限:理论分析、数学建模与 CPU/GPU 实测(2024)
译者序 本文翻译自 2024 年的一篇文章: LLM inference speed of light, 分析了大模型推理的速度瓶颈及量化评估方式,并给出了一些实测数据(我们在国产模型上的实测结果也大体吻合), 对理解大模型推理内部工…...

vue3 响应式 API:readonly() 与 shallowReadonly()
readonly() readonly()是一个用于创建只读代理对象的函数。它接受一个对象 (不论是响应式还是普通的) 或是一个 ref,返回一个原值的只读代理。 类型 function readonly<T extends object>(target: T ): DeepReadonly<UnwrapNestedRefs<T>>以下…...
迁移学习与知识蒸馏对比
应用场景不同 迁移学习:通常用于不同但相关的任务之间的知识迁移。特别是当目标任务的数据量不足时,可以从一个已经在大规模数据上训练好的模型中获取有用的特征或参数。典型场景包括计算机视觉任务,比如你在ImageNet上训练了一个ResNet&…...

【Java-反射】
什么是反射? JAVA反射机制是在运行状态中,创建任意一个类,能获取这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言…...

移动UI设计要求越来越高,最为设计师应如何迎头赶上
一、引言 在当今数字化高速发展的时代,移动设备已经成为人们生活中不可或缺的一部分。随着科技的不断进步和用户需求的日益增长,移动 UI 设计的要求也越来越高。作为移动 UI 设计师,我们面临着巨大的挑战,需要不断提升自己的能力…...

大数据-121 - Flink Time Watermark 详解 附带示例详解
点一下关注吧!!!非常感谢!!持续更新!!! 目前已经更新到了: Hadoop(已更完)HDFS(已更完)MapReduce(已更完&am…...

国行 iPhone 15 Pro 开启苹果 Apple Intelligence 教程
一、前言苹果在 iOS 18.1 测试版上正式开启了 Apple Intelligence 的内测,但国行设备因政策原因不支持,且国行设备在硬件上被锁定。不过,我们可以通过一些方法来破解国行 iPhone 15 Pro,使其能够开启 Apple Intelligence。 以下是…...

阿里云ACP云计算备考笔记 (5)——弹性伸缩
目录 第一章 概述 第二章 弹性伸缩简介 1、弹性伸缩 2、垂直伸缩 3、优势 4、应用场景 ① 无规律的业务量波动 ② 有规律的业务量波动 ③ 无明显业务量波动 ④ 混合型业务 ⑤ 消息通知 ⑥ 生命周期挂钩 ⑦ 自定义方式 ⑧ 滚的升级 5、使用限制 第三章 主要定义 …...

练习(含atoi的模拟实现,自定义类型等练习)
一、结构体大小的计算及位段 (结构体大小计算及位段 详解请看:自定义类型:结构体进阶-CSDN博客) 1.在32位系统环境,编译选项为4字节对齐,那么sizeof(A)和sizeof(B)是多少? #pragma pack(4)st…...

(二)TensorRT-LLM | 模型导出(v0.20.0rc3)
0. 概述 上一节 对安装和使用有个基本介绍。根据这个 issue 的描述,后续 TensorRT-LLM 团队可能更专注于更新和维护 pytorch backend。但 tensorrt backend 作为先前一直开发的工作,其中包含了大量可以学习的地方。本文主要看看它导出模型的部分&#x…...

Python爬虫(一):爬虫伪装
一、网站防爬机制概述 在当今互联网环境中,具有一定规模或盈利性质的网站几乎都实施了各种防爬措施。这些措施主要分为两大类: 身份验证机制:直接将未经授权的爬虫阻挡在外反爬技术体系:通过各种技术手段增加爬虫获取数据的难度…...
Spring Boot+Neo4j知识图谱实战:3步搭建智能关系网络!
一、引言 在数据驱动的背景下,知识图谱凭借其高效的信息组织能力,正逐步成为各行业应用的关键技术。本文聚焦 Spring Boot与Neo4j图数据库的技术结合,探讨知识图谱开发的实现细节,帮助读者掌握该技术栈在实际项目中的落地方法。 …...
rnn判断string中第一次出现a的下标
# coding:utf8 import torch import torch.nn as nn import numpy as np import random import json""" 基于pytorch的网络编写 实现一个RNN网络完成多分类任务 判断字符 a 第一次出现在字符串中的位置 """class TorchModel(nn.Module):def __in…...

在Mathematica中实现Newton-Raphson迭代的收敛时间算法(一般三次多项式)
考察一般的三次多项式,以r为参数: p[z_, r_] : z^3 (r - 1) z - r; roots[r_] : z /. Solve[p[z, r] 0, z]; 此多项式的根为: 尽管看起来这个多项式是特殊的,其实一般的三次多项式都是可以通过线性变换化为这个形式…...
ubuntu22.04 安装docker 和docker-compose
首先你要确保没有docker环境或者使用命令删掉docker sudo apt-get remove docker docker-engine docker.io containerd runc安装docker 更新软件环境 sudo apt update sudo apt upgrade下载docker依赖和GPG 密钥 # 依赖 apt-get install ca-certificates curl gnupg lsb-rel…...

一些实用的chrome扩展0x01
简介 浏览器扩展程序有助于自动化任务、查找隐藏的漏洞、隐藏自身痕迹。以下列出了一些必备扩展程序,无论是测试应用程序、搜寻漏洞还是收集情报,它们都能提升工作流程。 FoxyProxy 代理管理工具,此扩展简化了使用代理(如 Burp…...

Appium下载安装配置保姆教程(图文详解)
目录 一、Appium软件介绍 1.特点 2.工作原理 3.应用场景 二、环境准备 安装 Node.js 安装 Appium 安装 JDK 安装 Android SDK 安装Python及依赖包 三、安装教程 1.Node.js安装 1.1.下载Node 1.2.安装程序 1.3.配置npm仓储和缓存 1.4. 配置环境 1.5.测试Node.j…...