0


第一个搭建SpringBoot项目(连接mysql)

首先新建项目找到Spring Initializr 我使用的URL是https://start.spring.io这里最低的JDK版本是17,而且当网速不好的时候可能会显示超时,这里可以选用阿里云的镜像https://start.aliyun.com可以更快一些但是里面还是有一些区别的

我们这里选择Java语言,Maven框架

在这里我们选择一些我们需要用到的

这个版本可以选低一点更加稳定

进来之后我们需要先等pom文件加载,我们可以选择刷新Maven

加载完之后由于我们加载了MySQL所以还不能运行可以先注释掉,然后刷新maven

后面就可以运行了,但是它默认的是8080端口,有可能会有被占用的我们可以更改端口

后面既可以运行了

运行结果就是这样的后面没有了,刚开始由于我学习的时候和别人运行的不一样,还以为是卡住了,调试了好久好久,结果发现这就已经是运行了

下面我们就可以去页面看看结果了

用阿里云镜像的输出会有点不一样但是没有问题。

下面我们就可以创建一个测试类

新建一个TestController

  1. @RestController
  2. public class TestController {
  3. @GetMapping("/hello")
  4. public String hello(){
  5. return "hello word!";
  6. }
  7. }

再去页面观察

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

  1. package com.example.mysqldemo3.dao;
  2. import jakarta.persistence.*;
  3. import static jakarta.persistence.GenerationType.IDENTITY;
  4. @Entity
  5. @Table(name = "student")
  6. public class Student {
  7. @Id
  8. @Column(name = "id")
  9. @GeneratedValue(strategy = IDENTITY)
  10. private long id;
  11. @Column(name = "name")
  12. private String name;
  13. @Column(name = "email")
  14. private String email;
  15. @Column(name = "age")
  16. private int age;
  17. public long getId() {
  18. return id;
  19. }
  20. public void setId(long id) {
  21. this.id = id;
  22. }
  23. public String getName() {
  24. return name;
  25. }
  26. public void setName(String name) {
  27. this.name = name;
  28. }
  29. public String getEmail() {
  30. return email;
  31. }
  32. public void setEmail(String email) {
  33. this.email = email;
  34. }
  35. public int getAge() {
  36. return age;
  37. }
  38. public void setAge(int age) {
  39. this.age = age;
  40. }
  41. }

返回到接口补全代码

  1. package com.example.mysqldemo3.dao;
  2. import org.springframework.data.jpa.repository.JpaRepository;
  3. import org.springframework.stereotype.Repository;
  4. @Repository
  5. public interface StudentRepository extends JpaRepository<Student,Long> {
  6. }

Service层

StudentService

  1. package com.example.mysqldemo3.service;
  2. import com.example.mysqldemo3.dao.Student;
  3. public interface StudentService {
  4. Student getStudentById(long id);
  5. }

StudentServiceImpl

  1. package com.example.mysqldemo3.service;
  2. import com.example.mysqldemo3.dao.Student;
  3. import com.example.mysqldemo3.dao.StudentRepository;
  4. import jakarta.persistence.Id;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. @Service
  8. public class StudentServiceImpl implements StudentService{
  9. @Autowired
  10. private StudentRepository StudentRepository;
  11. @Override
  12. public Student getStudentById(long id) {
  13. return StudentRepository.findById(id).orElseThrow(RuntimeException::new) ;
  14. }
  15. }

controller层

  1. package com.example.mysqldemo3.controller;
  2. import com.example.mysqldemo3.dao.Student;
  3. import com.example.mysqldemo3.service.StudentService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.PathVariable;
  7. import org.springframework.web.bind.annotation.RestController;
  8. @RestController
  9. public class StudentController {
  10. @Autowired
  11. private StudentService studentService;
  12. @GetMapping("/student/{id}")
  13. public Student getStudentById(@PathVariable long id){
  14. return studentService.getStudentById(id);
  15. }
  16. }

连接数据库这些配置写在application里面

数据库

  1. spring.application.name=mysql-demo3
  2. server.port=8085
  3. spring.datasource.url=jdbc:mysql://localhost:3306/数据库名字?characterEncoding=utf-8
  4. spring.datasource.username=root
  5. spring.datasource.password=sgz250hhh

在数据库中填入数据

后面就可以去网页测试了

再往后我们需要做一些信息的隐藏,不想去展示这莫多的数据

创建

StudentDTO进行封装

  1. package com.example.mysqldemo3.dto;
  2. public class StudentDTO {
  3. private long id;
  4. private String name;
  5. private String email;
  6. public long getId() {
  7. return id;
  8. }
  9. public void setId(long id) {
  10. this.id = id;
  11. }
  12. public String getName() {
  13. return name;
  14. }
  15. public void setName(String name) {
  16. this.name = name;
  17. }
  18. public String getEmail() {
  19. return email;
  20. }
  21. public void setEmail(String email) {
  22. this.email = email;
  23. }
  24. }

新建converter将student的数据进行转换成DTO

StudentConverter

  1. package com.example.mysqldemo3.converter;
  2. import com.example.mysqldemo3.dao.Student;
  3. import com.example.mysqldemo3.dto.StudentDTO;
  4. public class StudentConverter {
  5. public static StudentDTO converStudent(Student student){
  6. //student转换成DTO对象
  7. StudentDTO studentDTO = new StudentDTO();
  8. studentDTO.setId(student.getId());
  9. studentDTO.setName(student.getName());
  10. studentDTO.setEmail(student.getEmail());
  11. return studentDTO;
  12. }
  13. }

新建

判断是否查询成功

Response

  1. package com.example.mysqldemo3;
  2. public class Response <T>{
  3. //返回后端的一些格式
  4. private T data;
  5. private boolean success;
  6. private String errorMsg;
  7. public static <K> Response<K> newSuccess(K data){
  8. //返回成功
  9. Response<K> response = new Response<>();
  10. response.setData(data);
  11. response.setSuccess(true);
  12. return response;
  13. }
  14. public static Response<Void> newFail(String errorMsg){
  15. //返回失败
  16. Response<Void> response = new Response<>();
  17. response.setErrorMsg(errorMsg);
  18. response.setSuccess(false);
  19. return response;
  20. }
  21. public T getData() {
  22. return data;
  23. }
  24. public void setData(T data) {
  25. this.data = data;
  26. }
  27. public boolean isSuccess() {
  28. return success;
  29. }
  30. public void setSuccess(boolean success) {
  31. this.success = success;
  32. }
  33. public String getErrorMsg() {
  34. return errorMsg;
  35. }
  36. public void setErrorMsg(String errorMsg) {
  37. this.errorMsg = errorMsg;
  38. }
  39. }

StudentService

  1. package com.example.mysqldemo3.service;
  2. import com.example.mysqldemo3.dao.Student;
  3. import com.example.mysqldemo3.dto.StudentDTO;
  4. public interface StudentService {
  5. StudentDTO getStudentById(long id);
  6. }

StudentServiceImpl

  1. package com.example.mysqldemo3.service;
  2. import com.example.mysqldemo3.converter.StudentConverter;
  3. import com.example.mysqldemo3.dao.Student;
  4. import com.example.mysqldemo3.dao.StudentRepository;
  5. import com.example.mysqldemo3.dto.StudentDTO;
  6. import jakarta.persistence.Id;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Service;
  9. @Service
  10. public class StudentServiceImpl implements StudentService{
  11. @Autowired
  12. private StudentRepository StudentRepository;
  13. @Override
  14. public StudentDTO getStudentById(long id) {
  15. Student student = StudentRepository.findById(id).orElseThrow(RuntimeException::new);
  16. return StudentConverter.converStudent(student);
  17. }
  18. }

StudentController

  1. package com.example.mysqldemo3.controller;
  2. import com.example.mysqldemo3.Response;
  3. import com.example.mysqldemo3.dao.Student;
  4. import com.example.mysqldemo3.dto.StudentDTO;
  5. import com.example.mysqldemo3.service.StudentService;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.GetMapping;
  8. import org.springframework.web.bind.annotation.PathVariable;
  9. import org.springframework.web.bind.annotation.RestController;
  10. @RestController
  11. public class StudentController {
  12. @Autowired
  13. private StudentService studentService;
  14. @GetMapping("/student/{id}")
  15. public Response<StudentDTO> getStudentById(@PathVariable long id){
  16. return Response.newSuccess(studentService.getStudentById(id));
  17. }
  18. }

刷新页面

就可以看见age被隐藏起来了

后面的就是增加删除和修改的操作可以使用Postman进行接口测试,可以直接官网下载

StudentServiceImpl

  1. package com.example.mysqldemo3.service;
  2. import com.example.mysqldemo3.converter.StudentConverter;
  3. import com.example.mysqldemo3.dao.Student;
  4. import com.example.mysqldemo3.dao.StudentRepository;
  5. import com.example.mysqldemo3.dto.StudentDTO;
  6. import jakarta.persistence.Id;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Service;
  9. import org.springframework.util.CollectionUtils;
  10. import org.springframework.util.StringUtils;
  11. import java.util.List;
  12. @Service
  13. public class StudentServiceImpl implements StudentService{
  14. @Autowired
  15. private StudentRepository StudentRepository;
  16. @Override
  17. public StudentDTO getStudentById(long id) {
  18. Student student = StudentRepository.findById(id).orElseThrow(RuntimeException::new);
  19. return StudentConverter.converStudent(student);
  20. }
  21. @Override
  22. public Long addNewStudent(StudentDTO studentDTO) {
  23. List<Student> studentList = StudentRepository.findByEmail(studentDTO.getEmail());
  24. if (!CollectionUtils.isEmpty(studentList)){
  25. throw new IllegalStateException("email:"+studentDTO.getEmail()+"has been taken");
  26. }
  27. Student student = StudentRepository.save(StudentConverter.converStudent(studentDTO));
  28. return student.getId();
  29. }
  30. @Override
  31. public void deleteStudentById(long id) {
  32. StudentRepository.findById(id).orElseThrow(()->new IllegalArgumentException("id"+id+"doesn`s exist!"));
  33. StudentRepository.deleteById(id);
  34. }
  35. @Override
  36. public StudentDTO updateStudentById(long id, String name, String email) {
  37. Student studentDB = StudentRepository.findById(id).orElseThrow(()->new IllegalArgumentException("id"+id+"doesn`s exist!"));
  38. if (StringUtils.hasLength(name) && !studentDB.getName().equals(name)){
  39. studentDB.setName(name);
  40. }
  41. if(StringUtils.hasLength(email) && !studentDB.getEmail().equals(email)){
  42. studentDB.setEmail(email);
  43. }
  44. Student student = StudentRepository.save(studentDB);
  45. return StudentConverter.converStudent(student);
  46. }
  47. }

StudentService

  1. package com.example.mysqldemo3.service;
  2. import com.example.mysqldemo3.dao.Student;
  3. import com.example.mysqldemo3.dto.StudentDTO;
  4. public interface StudentService {
  5. StudentDTO getStudentById(long id);
  6. Long addNewStudent(StudentDTO studentDTO);
  7. void deleteStudentById(long id);
  8. StudentDTO updateStudentById(long id, String name, String email);
  9. }

StudentRepository

  1. package com.example.mysqldemo3.dao;
  2. import org.springframework.data.jpa.repository.JpaRepository;
  3. import org.springframework.stereotype.Repository;
  4. import java.util.List;
  5. @Repository
  6. public interface StudentRepository extends JpaRepository<Student,Long> {
  7. List<Student> findByEmail(String emile);
  8. }

StudentConverter

  1. package com.example.mysqldemo3.converter;
  2. import com.example.mysqldemo3.dao.Student;
  3. import com.example.mysqldemo3.dto.StudentDTO;
  4. public class StudentConverter {
  5. public static StudentDTO converStudent(Student student){
  6. //student转换成DTO对象
  7. StudentDTO studentDTO = new StudentDTO();
  8. studentDTO.setId(student.getId());
  9. studentDTO.setName(student.getName());
  10. studentDTO.setEmail(student.getEmail());
  11. return studentDTO;
  12. }
  13. public static Student converStudent(StudentDTO StudentDTO){
  14. //student转换成DTO对象
  15. Student student = new Student();
  16. student.setName(StudentDTO.getName());
  17. student.setEmail(StudentDTO.getEmail());
  18. return student;
  19. }
  20. }

StudentController

  1. package com.example.mysqldemo3.controller;
  2. import com.example.mysqldemo3.Response;
  3. import com.example.mysqldemo3.dao.Student;
  4. import com.example.mysqldemo3.dto.StudentDTO;
  5. import com.example.mysqldemo3.service.StudentService;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.*;
  8. @RestController
  9. public class StudentController {
  10. @Autowired
  11. private StudentService studentService;
  12. @GetMapping("/student/{id}")
  13. public Response<StudentDTO> getStudentById(@PathVariable long id){
  14. return Response.newSuccess(studentService.getStudentById(id));
  15. }
  16. @PostMapping("/student")
  17. public Response<Long> addNewStudent(@RequestBody StudentDTO studentDTO){
  18. return Response.newSuccess(studentService.addNewStudent(studentDTO));
  19. }
  20. @DeleteMapping("/student/{id}")
  21. public void deleteStudentById(@PathVariable long id){
  22. studentService.deleteStudentById(id);
  23. }
  24. @PutMapping("/student/{id}")
  25. public Response<StudentDTO> updateStudentById(@PathVariable long id,@RequestParam(required = false) String name,@RequestParam(required = false) String email){
  26. return Response.newSuccess(studentService.updateStudentById(id,name,email));
  27. }
  28. }

最后就可以使用maven对文件进行打包了


本文转载自: https://blog.csdn.net/qq_63126439/article/details/141979018
版权归原作者 重生之苦练代码养女友 所有, 如有侵权,请联系我们删除。

“第一个搭建SpringBoot项目(连接mysql)”的评论:

还没有评论