@Data
public class Point {
private String x;
private String y;}
1.
2.
3.
4.
5.
record:
public record Point(String x, String y){}
1.
2.
我们创建一个简单的演示项目,依赖如图所示:
2、使用record替代普通DTO
我们在Spring MVC的控制器中可以用一个record的DTO来接受前端传递来的数据:
@RestController
@RequestMapping("/people")
public class PersonController {
private final PersonService personService;
public PersonController(PersonService personService){
this.personService= personService;}
@PostMapping
public ResponseEntity<Person> save(@RequestBody PersonDto personDto){
return ResponseEntity.ok(personService.save(personDto));}
@GetMapping("/findByLastName")
public ResponseEntity<List<PersonOnlyWithName>> findByLastName(String lastName){
return ResponseEntity.ok(personService.findByLastName(lastName));}}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
上面的PersonDto是一个record:
public record PersonDto(String firstName, String lastName,Integer age){}
@Service
public record PersonService(PersonRepository personRepository){//保存person
public Person save(PersonDto personDto){
Person person = new Person(personDto.firstName(), personDto.lastName(), personDto.age());
return personRepository.save(person);}//按照lastName查询people,返回值只有firstName和lastName
public List<PersonOnlyWithName> findByLastName(String lastName){
return personRepository.findByLastName(lastName);}}