DTO(Data Transfer Object)

이도훈·2025년 2월 17일

DTO(Data Transfer Object)란 무엇인가?

  • DTO(Data Transfer Object)는 뜻 그대로 데이터를 전달하는 객체이다. DTO는 단순히 데이터를 담아서 이동시키는 용도로 쓰인다.
  • 보통 Controller <-> Service 간에서 데이터를 전달하기 위해 사용되지만 Service <-> Repository 사이에서도 사용할 수 있다. Repository에서는 Entity를 다루는 것이 일반적이다.

예시코드 및 요청흐름

1. DTO 클래스

public class UserDTO {
    private String name;
    private int age;

    // 생성자, getter, setter
    public UserDTO(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() { return name; }
    public int getAge() { return age; }
}

DTO의 역할
데이터만 담는 객체 (비즈니스 로직 없음)

UserDTO 객체는 Controller와 Service 사이에서 데이터를 주고받는 용도
getter가 있어야 JSON 변환이 가능함 (Spring에서 자동으로 JSON 응답으로 변환할 때 필요)

2. Controller 클래스

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public UserDTO getUser() {
        return userService.getUser();  // DTO를 반환
    }
}

Controller의 역할
클라이언트의 요청을 처리하고 응답을 반환하는 역할
@RestController → JSON 형식으로 데이터를 반환하는 컨트롤러임을 명시
@GetMapping → /user 경로로 GET 요청이 오면 getUser() 메서드 실행
userService.getUser() 호출 → UserDTO를 받아서 JSON으로 변환해 응답

3. Service 클래스

import org.springframework.stereotype.Service;

@Service
public class UserService {
    public UserDTO getUser() {
        return new UserDTO("Alice", 25);  // DTO를 반환
    }
}

Service의 역할
비즈니스 로직 담당

예제에서는 간단하게 "Alice", 25 데이터를 UserDTO로 만들어 반환
실제 애플리케이션에서는 데이터베이스에서 사용자 정보를 가져와서 DTO로 변환하는 역할을 하게 됨

요청흐름

  1. GET /user 요청 → UserController.getUser()
  2. UserService.getUser() 호출 → UserDTO 생성
  3. UserDTO를 Controller에서 반환 → JSON 응답

결과(json 형식)

{
    "name": "Alice",
    "age": 25
}

0개의 댓글