record, DTO(Data Transfer Object)
공통점:둘 다 데이터를 전달하거나 표현하는 용도
차이점: 작성 방식·의도·불변성등
| 구분 | record | DTO (Data Transfer Object) |
|---|---|---|
| 도입 버전 | Java 14 (정식: 16) | 예전부터 사용 |
| 목적 | 불변(immutable)한 데이터 묶음 표현 | 계층 간 데이터 전달용 객체 |
| 특징 | 생성자, getter, equals, hashCode, toString 자동 생성 | Lombok 또는 직접 코드 작성 필요 |
| 불변성 | 기본적으로 final (수정 불가) | mutable(수정 가능) |
| 코드 길이 | 매우 짧음 | 보일러플레이트 코드 많음 |
| 적합한 용도 | 단순 조회 응답, API 응답 | 요청(request)나 서비스 계층에서 가공 필요 시 |
| 예시 사용 위치 | response DTO (Record) | request, entity 변환용 DTO (Class) |
// 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"
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} 요청 시, 프론트에 반환할 데이터 구조record 버전 (Response 전용)package com.niedu.dto;
public record NewsResponseDto(
Long id,
String title,
String summary,
String category,
String date
) {}
장점
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/create → NewsRequestDto | class (setter 필요) |
| 응답 DTO | /api/news/{id} → NewsResponseDto | record (불변, 가독성↑) |
| 항목 | record | DTO(class) |
|---|---|---|
| 선언 방식 | record NewsDto(...) {} | class NewsDto {} |
| 수정 가능 여부 | 불가능 | 가능 |
| 보일러플레이트 코드 | 최소화 | 많음(get/set/toString 등) |
| 주 사용 목적 | 응답(Response) | 요청(Request), 가공 |
| 가독성 | 매우 높음 | 보통 |