작성
·
715
0
선생님 안녀하세요!
강의보던 도중 헷갈리는 부분이 있어서 질문남깁니다.
수정을 할 때
1. 수정용 엔티티를 생성
2. 대상 엔티티를 조회
순서인데
이때
1. 수정용 엔티티를 생성 -> 받아온 새로운 데이터 엔티티
2. 대상 엔티티를 조회 -> 기존에 저장되어있던 엔티티
이렇게 이해해도 맞는걸까요?
// PATCH
@PatchMapping("/api/articles/{id}")
public ResponseEntity<Article> update(@PathVariable Long id,
@RequestBody ArticleForm dto){
// 1. 수정 용 엔티티 생성
Article article = dto.toEntity();
// 2. 대상 엔티티를 조회
Article target = articleRepository.findById(id).orElse(null);
// 3. 잘못된 요청 처리(대상이 없거나, id가 달느 경우)
if (target == null || id != article.getId()){
// 400, 잘못된 요청 응답!
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
}
// 4. 업데이트 및 정상응답(200)
target.patch(article);
Article updated = articleRepository.save(target);
return ResponseEntity.status(HttpStatus.OK).body(updated);
}
우왕 감사합니다 ㅎ