record

Seoyeon·2025년 10월 21일

백엔드

목록 보기
3/7

record, DTO(Data Transfer Object)
공통점:둘 다 데이터를 전달하거나 표현하는 용도
차이점: 작성 방식·의도·불변성등


record vs DTO(Data Transfer Object)

구분recordDTO (Data Transfer Object)
도입 버전Java 14 (정식: 16)예전부터 사용
목적불변(immutable)한 데이터 묶음 표현계층 간 데이터 전달용 객체
특징생성자, getter, equals, hashCode, toString 자동 생성Lombok 또는 직접 코드 작성 필요
불변성기본적으로 final (수정 불가)mutable(수정 가능)
코드 길이매우 짧음보일러플레이트 코드 많음
적합한 용도단순 조회 응답, API 응답요청(request)나 서비스 계층에서 가공 필요 시
예시 사용 위치response DTO (Record)request, entity 변환용 DTO (Class)

record 사용 예시

// record: 불변 DTO
public record UserResponseDto(
    Long id,
    String name,
    String email
) {}

-> 자동으로 다음이 생성

  • private final Long id;
  • private final String name;
  • private final String email;
  • public Long id() (getter)
  • equals(), hashCode(), toString()

사용 예시:

UserResponseDto dto = new UserResponseDto(1L, "sy", "sy@example.com");
System.out.println(dto.name()); // "sy"

일반 DTO (class 기반) 사용예시

public class UserDto {
    private Long id;
    private String name;
    private String email;

    public UserDto() {}

    public UserDto(Long id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }

    // getter, setter
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
}

사용 예시:

UserDto dto = new UserDto();
dto.setName("sy");
System.out.println(dto.getName()); // "sy"

record는 불변 → setter 없음
class DTO는 변경 가능 → setter로 값 수정 가능


예시 시나리오

  • 니듀의 뉴스 요약 정보를 전달하는 DTO
  • /api/news/{id} 요청 시, 프론트에 반환할 데이터 구조

1) record 버전 (Response 전용)

package com.niedu.dto;

public record NewsResponseDto(
    Long id,
    String title,
    String summary,
    String category,
    String date
) {}

장점

  • 단순하고 깔끔함
  • 응답 전용으로 안전 (수정 불가)
  • 직렬화/역직렬화 잘됨 (Spring 3.x+ 자동 지원)

2) class 버전 (Request/Service용 DTO)

package com.niedu.dto;

public class NewsRequestDto {
    private String title;
    private String content;
    private String category;

    public NewsRequestDto() {}

    public NewsRequestDto(String title, String content, String category) {
        this.title = title;
        this.content = content;
        this.category = category;
    }

    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }

    public String getContent() { return content; }
    public void setContent(String content) { this.content = content; }

    public String getCategory() { return category; }
    public void setCategory(String category) { this.category = category; }
}

실제 구조에서 쓰이는 방식

역할사용 예형태
요청 DTO/api/news/createNewsRequestDtoclass (setter 필요)
응답 DTO/api/news/{id}NewsResponseDtorecord (불변, 가독성↑)

요약 정리

항목recordDTO(class)
선언 방식record NewsDto(...) {}class NewsDto {}
수정 가능 여부불가능가능
보일러플레이트 코드최소화많음(get/set/toString 등)
주 사용 목적응답(Response)요청(Request), 가공
가독성매우 높음보통

0개의 댓글