Update 구현
MemoController 클래스에 아래 코드 추가
@PutMapping("/memos/{id}")
public Long updateMemo(@PathVariable Long id, @RequestBody MemoRequestDto requestDto) {
// 해당 메모가 DB에 존재하는지 확인
if(memoList.containsKey(id)) {
// 해당 메모 가져오기
Memo memo = memoList.get(id);
// memo 수정
memo.update(requestDto);
return memo.getId();
} else {
throw new IllegalArgumentException("선택한 메모는 존재하지 않습니다.");
}
}
Memo memo = memoList.get(id) 이것은 얕은 복사로서 memo 객체와 memoList.get(id)의 객체는 같은 주소를 바라보고 있다. 즉 memo 객체를 이용해 내용을 수정하면 memoList 안에 있는 그 객체도 영향을 받는다는 뜻이다.
Memo 클래스에 update 메서드 추가
public void update(MemoRequestDto requestDto) {
this.username = requestDto.getUsername();
this.contents = requestDto.getContents();
}
Delete 구현
@DeleteMapping("/memos/{id}")
public Long deleteMemo(@PathVariable Long id) {
// 해당 메모가 DB에 존재하는지 확인
if(memoList.containsKey(id)) {
// 해당 메모 삭제하기
memoList.remove(id);
return id;
} else {
throw new IllegalArgumentException("선택한 메모는 존재하지 않습니다.");
}
}
'Spring 입문주차 > 1주차' 카테고리의 다른 글
18. SQL (0) | 2024.08.14 |
---|---|
17. Database (0) | 2024.08.14 |
15. Create, Read 구현하기(DTO) (0) | 2024.08.14 |
14. 메모장 프로젝트 설계 (0) | 2024.08.14 |
13. HTTP 데이터를 객체로 처리하는 방법 (0) | 2024.08.14 |