当前位置: 首页 > news >正文

第一个搭建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对文件进行打包了

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • layui监听table表单的多选框
  • 2414. Length of the Longest Alphabetical Continuous Substring
  • k8s集群部署:安装 kubeadm
  • 助力新能源汽车产业发展,2025第五届广州国际新能源汽车产业智能制造技术展览会将于11月在广州召开
  • 告别页面卡顿:Web Worker 助你解决前端性能瓶颈
  • linux进程间通信——进程间通信概念、最基本通信——管道文件
  • 基于微信小程序点餐、外卖系统的设计与实现 (源码+lw+参考文档+核心代码讲解等)
  • MacOS wine中文乱码问题
  • 负载均衡调度器--LVS
  • qt怎么格式化字符串?
  • 音视频入门基础:WAV专题(11)——FFmpeg源码中计算WAV音频文件每个packet的pts_time、dts_time的实现
  • 【开发工具】Maven Dependency Helper:IntelliJ IDEA的贴心助手,助力梳理依赖关系
  • Numba最近邻插值(CPU+ GPU + Z轴切块 + XYZ轴切块 + 多线程)
  • 论文解读:《LAMM: Label Alignment for Multi-Modal Prompt Learning》
  • 使用FFmpeg实现简单的拉流、推流、视频解码Demo
  • 【干货分享】SpringCloud微服务架构分布式组件如何共享session对象
  • 4. 路由到控制器 - Laravel从零开始教程
  • 8年软件测试工程师感悟——写给还在迷茫中的朋友
  • iOS 颜色设置看我就够了
  • Java,console输出实时的转向GUI textbox
  • js作用域和this的理解
  • Lsb图片隐写
  • 初识 webpack
  • 观察者模式实现非直接耦合
  • 微服务入门【系列视频课程】
  • 小试R空间处理新库sf
  • 白色的风信子
  • JavaScript 新语法详解:Class 的私有属性与私有方法 ...
  • scrapy中间件源码分析及常用中间件大全
  • ​queue --- 一个同步的队列类​
  • ​探讨元宇宙和VR虚拟现实之间的区别​
  • ​总结MySQL 的一些知识点:MySQL 选择数据库​
  • #if #elif #endif
  • #if和#ifdef区别
  • #职场发展#其他
  • (02)Cartographer源码无死角解析-(03) 新数据运行与地图保存、加载地图启动仅定位模式
  • (1/2) 为了理解 UWP 的启动流程,我从零开始创建了一个 UWP 程序
  • (每日持续更新)信息系统项目管理(第四版)(高级项目管理)考试重点整理第3章 信息系统治理(一)
  • (数位dp) 算法竞赛入门到进阶 书本题集
  • (原+转)Ubuntu16.04软件中心闪退及wifi消失
  • (轉貼) 寄發紅帖基本原則(教育部禮儀司頒布) (雜項)
  • (自用)网络编程
  • .babyk勒索病毒解析:恶意更新如何威胁您的数据安全
  • .NET开源全面方便的第三方登录组件集合 - MrHuo.OAuth
  • .NET文档生成工具ADB使用图文教程
  • /usr/bin/python: can't decompress data; zlib not available 的异常处理
  • ??myeclipse+tomcat
  • @entity 不限字节长度的类型_一文读懂Redis常见对象类型的底层数据结构
  • [023-2].第2节:SpringBoot中接收参数相关注解
  • [AI Google] 使用 Gemini 取得更多成就:试用 1.5 Pro 和更多智能功能
  • [C#]winform制作圆形进度条好用的圆环圆形进度条控件和使用方法
  • [C语言]-基础知识点梳理-文件管理
  • [Delphi]一个功能完备的国密SM4类(TSM4)[20230329更新]
  • [GN] 后端接口已经写好 初次布局前端需要的操作(例)
  • [IOI2007 D1T1]Miners 矿工配餐