반응형
- POST
1
2
3
4
5
6
7
8
9
10
11
|
@PostMapping("/employees")
ResponseEntity<?> newEmployee(@RequestBody Employee newEmployee) {
EntityModel<Employee> entityModel = EntityModel.of(repository.save(newEmployee),
linkTo(methodOn(EmployeeController.class).one(newEmployee.getId())).withSelfRel(),
linkTo(methodOn(EmployeeController.class).all()).withRel("employees"));
return ResponseEntity
.created(entityModel.getRequiredLink(IanaLinkRelations.SELF).toUri())
.body(entityModel);
}
|
- GET
1
2
3
4
5
6
7
8
9
10
11
|
@GetMapping("/employees")
public CollectionModel<EntityModel<Employee>> all() {
List<EntityModel<Employee>> employees = repository.findAll().stream()
.map(employee -> EntityModel.of(employee,
linkTo(methodOn(EmployeeController.class).one(employee.getId())).withSelfRel(),
linkTo(methodOn(EmployeeController.class).all()).withRel("employees")))
.collect(Collectors.toList());
return CollectionModel.of(employees, linkTo(methodOn(EmployeeController.class).all()).withSelfRel());
}
|
1
2
3
4
5
6
7
8
9
10 |
@GetMapping("/employees/{id}")
public EntityModel<Employee> one(@PathVariable Long id) {
Employee employee = repository.findById(id)
.orElseThrow(() -> new EmployeeNotFoundException(id));
return EntityModel.of(employee,
linkTo(methodOn(EmployeeController.class).one(employee.getId())).withSelfRel(),
linkTo(methodOn(EmployeeController.class).all()).withRel("employees"));
}
|
- PUT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
@PutMapping("/employees/{id}")
ResponseEntity<?> replaceEmployee(@RequestBody Employee newEmployee, @PathVariable Long id) {
Employee updatedEmployee = repository.findById(id)
.map(employee -> repository.save(newEmployee))
.orElseGet(() -> {
newEmployee.setId(id);
return repository.save(newEmployee);
});
EntityModel<Employee> entityModel = EntityModel.of(updatedEmployee,
linkTo(methodOn(EmployeeController.class).one(updatedEmployee.getId())).withSelfRel(),
linkTo(methodOn(EmployeeController.class).all()).withRel("employees"));
return ResponseEntity
.created(entityModel.getRequiredLink(IanaLinkRelations.SELF).toUri())
.body(entityModel);
}
|
- DELETE
1
2
3
4
5
6
|
@DeleteMapping("/employees/{id}")
ResponseEntity<?> deleteEmployee(@PathVariable Long id) {
repository.deleteById(id);
return ResponseEntity.noContent().build();
}
|
아래 기능은 표현모델 어셈블러(Representation model assembler)
를 생성하여 대체할 수 있습니다.
관련해서는 다음 포스팅에 자세히 올리겠습니다.
EntityModel.of(employee,
linkTo(methodOn(EmployeeController.class).one(employee.getId())).withSelfRel(),
linkTo(methodOn(EmployeeController.class).all()).withRel("employees"));
반응형
'- Spring' 카테고리의 다른 글
[ERROR] Error creating bean with name 'repositoryController' / At least one JPA metamodel must be present! (2) | 2020.10.16 |
---|---|
[Spring Hateoas1.2] ModelAssembler, ModelProcessor (0) | 2020.09.02 |
[Spring Hateoas 1.2] RepresentationModel 테스트 (0) | 2020.08.24 |
[Spring Hateoas 1.2] 소개 및 프로젝트 설정 (0) | 2020.08.21 |
[Spring Batch] cannot be cast to org.springframework.batch.item.~ (0) | 2020.07.31 |