DTO(Data Transfer Object)
는 계층 간 데이터 전송을 목적으로 하는 객체로 주로 Controller와 Service 사이에서 데이터를 주고받을 때 사용된다.
DTO
를 활용하면 불필요한 엔터티 노출을 방지하고, 응답 성능을 최적화할 수 있다.
Java 14부터 도입된 record
를 활용하면 불변성과 간결한 코드를 동시에 얻을 수 있다!
✅ record 기반 DTO의 특징
- Getter, Setter 없이도 필드 값 조회 가능
- 불변 객체로 데이터 변경을 방지
- equals(), hashCode(), toString() 등 자동으로 구현
기존 클래스 기반 DTO
vs 레코드 기반 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());
}
}
public record UserDTO(String name, String email) {
public static UserDTO fromEntity(User user) {
return new UserDTO(user.getName(), user.getEmail());
}
}
DTO에서 자주 사용되는 구현 패턴을 알아보자 🔍
(메소드 명은 편의에 맞게 바꿔서 쓰기도 한다)
데이터베이스에서 가져온 Entity 데이터를 Response 응답에 필요한 형식인 DTO 형식으로 변환할 때 주로 사용된다.
public record UserResponseDTO(String name, String email) {
public static UserResponseDTO from(User user) {
return new UserResponseDTO(user.getName(), user.getEmail());
}
}
여러 인자를 받아 DTO 객체를 생성할 때 사용된다.
이 패턴은 DTO 객체를 간편하게 생성할 수 있도록 돕는다.
public record UserDTO(String name, String email) {
public static UserDTO of(String name, String email) {
return new UserDTO(name, email);
}
}
Request 요청 받은 DTO 객체를 Entity 객체로 변환할 때 사용된다.
DTO에서 데이터를 추출하여 Entity 객체로 변환하여 데이터베이스에 저장할 수 있도록 한다.
public record UserRequestDTO(String name, String email) {
public User toEntity() {
return new User(name, email);
}
}
너무 잘 하고 있어요 ㅠㅠ
4학년 되고 면접에 대해서 조금씩 진행할수록
이런 것들에 대한 기본 개념 익힘을 통해 내가 왜 이걸 사용하는지.. 알고 쓰는게 제일 중요한거같아요..
화이팅입니다!!1