DTO (Data Transfer Object)

Metronon·2024년 12월 30일
0

REST-API

목록 보기
9/12
post-thumbnail

웹서비스에서 데이터를 저장하기 위해선 객체(Entity)를 만들어야 한다.

서버에는 객체의 컬럼에 맞게 데이터를 저장하게 된다.
하지만 웹에서 객체에 포함된 모든 데이터를 불러올 필요는 없다.
더욱이 민감한 정보라면 노출되지 않게 할 필요가 있다.

여기서 DTO라는 객체를 만들면 원하는 데이터만을 꺼내 사용할 수 있다.

DTO의 정의

DTO(Data Transfer Object)란 계층간의 데이터 전송을 위한 객체이다.
주로 다음과 같은 상황에서 사용한다.

  • 컨트롤러와 서비스 계층 사이에서 데이터 전달
  • 서비스와 리포지터리 계층 사이에서 데이터 전달
  • API에서의 응답을 위한 데이터 구조화

DTO 사용 예시

사용자 Entity

@Getter
@Setter
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique=true)
    private String username;

    private String password;

    @Column(unique=true)
    private String email;
    
    private LocalDateTime joinedDate;
}

사용자 프로필 DTO

@Getter
@builder
public class UserProfileDto {
	@JsonProperty("nickname") // Key의 이름을 바꿀 수 있다.
	private String username;
    
    private String email;
    
    private String formattedJoinedDate
    
    public static UserProfileDto from(User user) {
    	return UserProfileDto.builder()
        	.username(user.getUsername())
            .email(user.getEmail())
            .formattedJoinedDate(
            	user.getJoinedDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
            )
            .build();
    }
}

DTO 사용 장점

  1. 원하는 데이터만을 노출해 원치 않는 데이터의 노출을 은닉할 수 있다.
  2. 데이터의 형식, 자료형을 변환해 노출할 수 있다.
  3. @NotBlank, @Size등으로 유효성 검증이 가능하다.
profile
비전공 개발 지망생의 벨로그입니다!

0개의 댓글