DTO(Data Transfer Object)는 데이터 전송 및 이동을 위해 생성되는 객체를 말합니다. 아래 예시를 통해 자세히 살펴보도록 하겠습니다.
- Client에서 보내오는 데이터를 객체로 처리할 때 사용
- 서버의 계층간의 이동에도 사용
- DB 와의 소통을 담당하는 Java 클래스(Entity)를 그대로 Client에 반환하는 것이 아니라 DTO로 한번 변환한 후 반환할 때 사용
일반적으로 Request의 데이터를 처리할 때 사용되는 객체는 RequestDto, Response를 할 때 사용되는 객체는 ResponseDto 라는 이름을 붙여 DTO 클래스를 만들 수 있습니다.
메모장 프로젝트
메모장 기능 설계
1. 접속 하자마자 메모 전체 목록 조회하기
a. GET API를 사용해서 메모 목록 불러오기
2. 메모 생성하기
a. POST API 사용해서 메모 신규 생성하기
b. 생성된 메모 반환
3. 메모 변경하기
a. PUT API 사용해서 메모 내용 변경하기
b. 사용자가 클릭한 메모가 DB에 존재하는지 확인하기
c. 해당 메모 내용 변경
4. 메모 삭제하기
a. DELETE API 사용해서 메모 삭제하기
b. 사용자가 삭제하려는 메모가 DB에 존재하는지 확인하기
c. DB에서 해당 메모 삭제
메모장 API
기능 | Method | URL | Return |
메모 생성하기 | POST | /api/memos | MemoResponseDto |
메모 조회하기 | GET | /api/memos | List<MemoResponseDto> |
메모 변경하기 | PUT | /api/memos/{id} | Long |
메모 삭제하기 | DELETE | /api/memos/{id} | Long |
1. 메모 데이터를 저장할 Memo 클래스 생성
entity 패키지 > Memo 클래스
@Getter
@Setter
@NoArgsConstructor
public class Memo {
private Long id;
private String username;
private String contents;
public Memo(MemoRequestDto requestDto) {
this.username = requestDto.getUsername();
this.contents = requestDto.getContents();
}
public void update(MemoRequestDto requestDto) {
this.username = requestDto.getUsername();
this.contents = requestDto.getContents();
}
}
2. 메모 생성하기 API를 받을 수 있는 Controller와 메서드 생성
controller 패키지 > MemoController 클래스
@RestController
@RequestMapping("/api")
public class MemoController {
@PostMapping("/memos")
public MemoResponseDto createMemo(@RequestBody MemoRequestDto requestDto) {
return memoResponseDto;
}
}
3. Client에 데이터를 반환할 때 사용할 dto 패키지 > MemoResponseDto 클래스 생성
@Getter
public class MemoResponseDto {
private Long id;
private String username;
private String contents;
public MemoResponseDto(Memo memo) {
this.id = memo.getId();
this.username = memo.getUsername();
this.contents = memo.getContents();
}
}
4. Client의 요청 데이터를 받아줄 dto 패키지 > MemoRequestDto 클래스 생성
@Getter
public class MemoRequestDto {
private String username;
private String contents;
}
5. DB와 연결을 하지 않았기 때문에 메모 데이터를 저장할 Java 컬렉션을 생성하고 메모 생성 로직을 작성 합니다.(POST)
@RestController
@RequestMapping("/api")
public class MemoController {
// DB 대신 사용
private final Map<Long, Memo> memoList = new HashMap<>();
@PostMapping("/memos")
public MemoResponseDto createMemo(@RequestBody MemoRequestDto requestDto) {
// RequestDto -> Entity
Memo memo = new Memo(requestDto);
// Memo Max ID Check(ID 값으로 메모를 구분, 중복X)
Long maxId = memoList.size() > 0 ? Collections.max(memoList.keySet()) + 1 : 1;
memo.setId(maxId);
// DB 저장
memoList.put(memo.getId(), memo);
// Entity -> ResponseDto
MemoResponseDto memoResponseDto = new MemoResponseDto(memo);
return memoResponseDto;
}
}
6. DB 역할을 하는 memoList를 조회하여 List<MemoResponseDto>로 변환한 후 반환(GET)
@RestController
@RequestMapping("/api")
public class MemoController {
@GetMapping("/memos")
public List<MemoResponseDto> getMemos() {
// Map -> List
List<MemoResponseDto> reponseList = memoList.values().stream()
.map(MemoResponseDto::new).toList();
return reponseList;
}
}
7. Update 구현(PUT)
@RestController
@RequestMapping("/api")
public class 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("선택한 메모는 존재하지 않습니다.");
}
}
}
8. Delete 구현(DELETE)
@RestController
@RequestMapping("/api")
public class MemoController {
@DeleteMapping("/memos/{id}")
public Long deleteMemo(@PathVariable Long id) {
// 해당 메모가 DB에 존재하는지 확인
if (memoList.containsKey(id)) {
// 해당 메모 삭제하기
memoList.remove(id);
return id;
} else {
throw new IllegalArgumentException("선택한 메모는 존재하지 않습니다.");
}
}
'Spring' 카테고리의 다른 글
[Spring] 3 Layer Architecture (0) | 2024.10.02 |
---|---|
[Spring] JDBC란 무엇이고 어떻게 사용할까? (1) | 2024.09.30 |
[Spring] HTTP 데이터를 객체로 처리하는 방법 (0) | 2024.09.27 |
[Spring] Path Variable 과 Request Param (0) | 2024.09.26 |
[Spring] Jackson 이란 무엇인가? (0) | 2024.09.26 |