[Spring Boot3] DTO 어디까지 써봤나?🤔🔄 (from, of, toEntity)

hhh·2025년 3월 22일
2

스프링부트🌱

목록 보기
6/13
post-thumbnail

1. DTO(Data Transfer Object)란?

DTO(Data Transfer Object)계층 간 데이터 전송을 목적으로 하는 객체로 주로 Controller와 Service 사이에서 데이터를 주고받을 때 사용된다.

2. 엔티티 vs DTO

DTO를 활용하면 불필요한 엔터티 노출을 방지하고, 응답 성능을 최적화할 수 있다.

2. record 기반 DTO의 도입

Java 14부터 도입된 record를 활용하면 불변성과 간결한 코드를 동시에 얻을 수 있다!

record 기반 DTO의 특징

  • Getter, Setter 없이도 필드 값 조회 가능
  • 불변 객체로 데이터 변경을 방지
  • equals(), hashCode(), toString() 등 자동으로 구현

기존 클래스 기반 DTO vs 레코드 기반 DTO

  • 기존 DTO (클래스 기반)
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class UserDTO {
    private String name;
    private String email;

    public static UserDTO fromEntity(User user) {
        return new UserDTO(user.getName(), user.getEmail());
    }
}
  • 레코드 기반 DTO
public record UserDTO(String name, String email) {
    public static UserDTO fromEntity(User user) {
        return new UserDTO(user.getName(), user.getEmail());
    }
}

3. DTO 주요 활용 패턴

DTO에서 자주 사용되는 구현 패턴을 알아보자 🔍
(메소드 명은 편의에 맞게 바꿔서 쓰기도 한다)

1️⃣ from (Entity -> DTO 변환)

데이터베이스에서 가져온 Entity 데이터를 Response 응답에 필요한 형식인 DTO 형식으로 변환할 때 주로 사용된다.

public record UserResponseDTO(String name, String email) {
    public static UserResponseDTO from(User user) {
        return new UserResponseDTO(user.getName(), user.getEmail());
    }
}

2️⃣ of (DTO 객체 생성)

여러 인자를 받아 DTO 객체를 생성할 때 사용된다.
이 패턴은 DTO 객체를 간편하게 생성할 수 있도록 돕는다.

public record UserDTO(String name, String email) {
    public static UserDTO of(String name, String email) {
        return new UserDTO(name, email);
    }
}

3️⃣ toEntity (DTO -> Entity 변환)

Request 요청 받은 DTO 객체를 Entity 객체로 변환할 때 사용된다.
DTO에서 데이터를 추출하여 Entity 객체로 변환하여 데이터베이스에 저장할 수 있도록 한다.

public record UserRequestDTO(String name, String email) {
    public User toEntity() {
        return new User(name, email);
    }
}

4. 요약

profile
백엔드개발자의 개발 기록 끄적끄적✏️

1개의 댓글

comment-user-thumbnail
2025년 3월 24일

너무 잘 하고 있어요 ㅠㅠ
4학년 되고 면접에 대해서 조금씩 진행할수록
이런 것들에 대한 기본 개념 익힘을 통해 내가 왜 이걸 사용하는지.. 알고 쓰는게 제일 중요한거같아요..
화이팅입니다!!1

답글 달기