首先新建项目找到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{
@Autowired
private StudentRepository StudentRepository;
@Override
public 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 {
@Autowired
private 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{
@Autowired
private StudentRepository StudentRepository;
@Override
public 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 {
@Autowired
private 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{
@Autowired
private StudentRepository StudentRepository;
@Override
public StudentDTO getStudentById(long id) {
Student student = StudentRepository.findById(id).orElseThrow(RuntimeException::new);
return StudentConverter.converStudent(student);
}
@Override
public 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();
}
@Override
public void deleteStudentById(long id) {
StudentRepository.findById(id).orElseThrow(()->new IllegalArgumentException("id"+id+"doesn`s exist!"));
StudentRepository.deleteById(id);
}
@Override
public 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 {
@Autowired
private 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对文件进行打包了