DTO란?
“계층 간 데이터를 안전하고 명확하게 전달하기 위한 객체”
DTO와 Entity의 차이
Entity
- DB 테이블과 직접 연결된 원본 데이터
DTO
- 사용자에게 보여주길 원하는 데이터 (* 필요한 데이터만 전달)
Entity를 직접 사용하면 안되는 이유
- Entity는 DB 구조이다. 이를 그대로 사용자에게 전송할 경우, 보안 문제 발생 가능! (DB 구조(Entity) ≠ API 응답 구조)
- Entity 변경시, API 응답이 변경되어 프론트엔드 에러 발생 가능!
DTO 장점
- API 안정성 (DTO 외 코드가 변경되어도 API 형식 유지 가능)
- 보안 (민감 정보 숨김)
- 필요한 데이터 전달 (응답 크기 감소)
- 유지보수 편리
- 무한 참조 방지 (JPA 연관관계 문제 해결)
프로젝트 구현
public record OrderRequest(
Long productId,
int quantity
) {
}
public record OrderResponse(
Long orderId,
String productName,
int quantity
) {
public static OrderResponse from(Order order) {
return new OrderResponse(
order.getId(),
order.getProduct().getName(),
order.getQuantity()
);
}
}
public record ProductRequest(
String name,
int price,
int stock
) {
}
public record ProductResponse(
Long id,
String name,
int price,
int stock
) {
public static ProductResponse from(Product product) {
return new ProductResponse(
product.getId(),
product.getName(),
product.getPrice(),
product.getStock()
);
}
}
코드 설명
record 문법 참고 : https://record47584.tistory.com/7
JAVA 문법 - record
record란?“데이터 저장 목적 객체를 간단하게 만들기 위한 Java 문법”(자바 16부터 정식 지원) record가 자동 생성하는 것생성자gettrt 비슷한 메서드 (기존 getter와 이름이 다르다. getId()가 아닌 id().
record47584.tistory.com
'Spring > - [시리즈] 간단한 CRUD 구현하기' 카테고리의 다른 글
| CRUD 구현 7 - Controller 구현 (0) | 2026.05.15 |
|---|---|
| CRUD 구현 6 - Service 구현 (0) | 2026.05.15 |
| CRUD 구현 4 - Repository 구현 (0) | 2026.05.14 |
| CRUD 구현 3 - Entity 구현 (0) | 2026.05.14 |
| CRUD 구현 2 - DB 세팅 및 ERD (mySql, JPA) (0) | 2026.05.12 |