작성
·
483
14
소스를 공유합니다.
@PostMapping
public ResponseEntity createEvent(@RequestBody @Valid EventDto event, Errors errors) {
if(errors.hasErrors()) {
return ResponseEntity.badRequest().body(errors);
}
eventValidator.validate(event, errors);
if(errors.hasErrors()) {
return ResponseEntity.badRequest().body(errors);
}
Event newEvent = eventRepository.save(modelMapper.map(event, Event.class));
Integer eventId = newEvent.getId();
newEvent.update();
WebMvcLinkBuilder selfLinkBuilder = linkTo(EventController.class).slash(eventId);
URI createdUri = selfLinkBuilder.toUri();
EntityModel eventResource = EntityModel.of(newEvent);
eventResource.add(linkTo(EventController.class).slash(eventId).withSelfRel());
eventResource.add(linkTo(EventController.class).withRel("query-events"));
eventResource.add(selfLinkBuilder.withRel("update-event"));
return ResponseEntity.created(createdUri).body(eventResource);
}
답변 2
3
혹은 아래와 같이 처리하기도 하였습니다.
@PostMapping
public ResponseEntity createEvent(@RequestBody @Valid EventDto event, Errors errors) {
if(errors.hasErrors()) {
return ResponseEntity.badRequest().body(errors);
}
eventValidator.validate(event, errors);
if(errors.hasErrors()) {
return ResponseEntity.badRequest().body(errors);
}
Event newEvent = eventRepository.save(modelMapper.map(event, Event.class));
Integer eventId = newEvent.getId();
newEvent.update();
WebMvcLinkBuilder selfLinkBuilder = linkTo(EventController.class).slash(eventId);
URI createdUri = selfLinkBuilder.toUri();
List<Link> links = Arrays.asList(
selfLinkBuilder.slash(eventId).withSelfRel(),
selfLinkBuilder.withRel("query-events"),
selfLinkBuilder.withRel("update-event")
);
EntityModel eventResource = EntityModel.of(newEvent, links);
eventResource.add();
eventResource.add();
eventResource.add(selfLinkBuilder.withRel("update-event"));
return ResponseEntity.created(createdUri).body(eventResource);
}
1
감사합니다. 저도 안되서 Spring hateoas docs를 보니깐 ResourceSupport, Resource 객체가 1.2.1 버전부터 각각 RepresentationModel, EntityModel로 변경되었더라구요.
다른 수강생분들도 본인 hateoas 버전 확인해보시고 1.2.1 이라면 kmh님이작성한 코드로 진행하시면 될 것 같습니다.
https://docs.spring.io/spring-hateoas/docs/1.2.0/reference/html/#migrate-to-1.0.changes