본문 바로가기

- Spring

[Spring Hateoas 1.2] HTTP Method에 헤이토스 적용

반응형

- 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"));

반응형