【发布时间】:2020-08-27 13:51:31
【问题描述】:
我是 Spring Boot 的新手,我一直在学习本教程 (https://www.youtube.com/watch?v=vtPkZShrvXQ),但我被困在这一点上。任何指针将不胜感激。
我可以发出 POST 请求,并在 Postman 中看到请求以 200 状态通过,但是当我发出 GET 请求以检索 JSON 数据时,我看到 200 状态,但在 Postman 中没有响应控制台,只有一个“ø”——有人知道我做错了什么吗?
这是我的控制器:
package com.example.demo.api;
import com.example.demo.model.Person;
import com.example.demo.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.UUID;
@RequestMapping("/api/v1/person")
@RestController
public class PersonController {
//reference to the service
private final PersonService personService;
@Autowired
public PersonController(PersonService personService) {
this.personService = personService;
}
//POST
@PostMapping
public void addPerson(@RequestBody Person person) {
personService.addPerson(person);
}
//GET
@GetMapping
public List<Person> getAllPeople() {
return personService.getAllPeople();
}
}
这里是服务文件:
package com.example.demo.service;
import com.example.demo.dao.PersonDao;
import com.example.demo.model.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Service
public class PersonService {
private final PersonDao personDao;
@Autowired
public PersonService(@Qualifier("fakeDao") PersonDao personDao) {
this.personDao = personDao;
}
public int addPerson(Person person) {
return personDao.insertPerson(person);
}
public List<Person> getAllPeople() {
return personDao.selectAllPeople();
}
public Optional<Person> getPersonById(UUID id){
return personDao.selectPersonById(id);
}
}
这是界面:
package com.example.demo.dao;
import com.example.demo.model.Person;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
//insert person into database
public interface PersonDao {
//this inserts a person with an id
int insertPerson(UUID id, Person person);
//this inserts a person that does not have an id. An idea is generated:
default int insertPerson(Person person) {
UUID id = UUID.randomUUID();
return insertPerson(id, person);
}
List<Person> selectAllPeople();
Optional<Person> selectPersonById(UUID id);
int deletePersonById(UUID id);
int updatePersonById(UUID id, Person person);
}
【问题讨论】:
-
顺便说一下,如果你使用 JPA,Spring Data JPA 会自动为你生成你的 DAO 实现并且可以提供有用的帮助,比如让你说
@GetMapping("/{id}")... @PathVariable("id") Person person。此外,从数据库表示中分离出 DTO 类 (PersonDto) 通常是一个好主意,这样您就可以根据需要对其中任何一个进行更改而不会破坏任何内容。 MapStruct 是一种工具,可以帮助您与 DTO 表示进行转换。 -
你能澄清你的第二段吗?哪个请求返回的是空正文?
-
GET 请求返回的是空正文。
标签: java spring spring-boot postman