용도 메서드명 예시
DTO → Entity toEntity()
Entity → DTO from(entity: Entity)
두 인자 이상 필요 of(request, team, createdBy) 도 자주 씀
주로 CreateRequest / UpdateRequest 같은 요청 DTO에서
도메인 객체로 변환할 때 사용.
data class ContiCreateRequest(...) {
companion object {
fun toEntity(request: ContiCreateRequest, team: Team, createdBy: Long): Conti {
return Conti(
title = request.title,
date = request.date,
lyrics = request.lyrics,
sheetMusicUrl = request.sheetMusicUrl ?: "",
musicLink = request.musicLink ?: "",
team = team,
createdBy = createdBy
)
}
}
}
Entity → 응답 DTO로 변환할 때 주로 사용.
예: Conti → ContiResponse, ContiDetailResponse 등
data class ContiResponse(
val id: Long,
val title: String,
val date: LocalDate
) {
companion object {
fun from(entity: Conti): ContiResponse {
return ContiResponse(
id = entity.id!!,
title = entity.title,
date = entity.date
)
}
}
}
of(...)
– 복잡한 입력 값이 여럿일 때 (Entity, DTO, 외부 인자 등)DTO + 연관 객체들 + 외부 파라미터가 함께 필요한 경우
즉, 생성자에 들어가는 인자가 많고, 단순 toEntity()보다 컨텍스트가 섞이는 경우에 좋음
data class ContiCreateRequest(...) {
companion object {
fun of(request: ContiCreateRequest, team: Team, userId: Long): Conti {
return Conti(
title = request.title,
date = request.date,
lyrics = request.lyrics,
sheetMusicUrl = request.sheetMusicUrl ?: "",
musicLink = request.musicLink ?: "",
team = team,
createdBy = userId
)
}
}
}
메서드 | 위치 | 사용 시기 | 설명 |
---|---|---|---|
toEntity() | Request DTO → Entity | 생성/수정 요청 처리 시 | 가장 많이 쓰는 기본형 |
from() | Entity → Response DTO | 응답 DTO 만들 때 | 응답 포맷을 깔끔하게 분리 |
of() | 복합 상황 전용 | 여러 인자 필요 시 | DTO + 연관 Entity + 외부 파라미터 등 |
효과 | 이유 |
---|---|
코드 간결함 | 생성자 직접 호출보다 깔끔 |
책임 분리 | 변환 책임은 DTO에서, 저장 책임은 Service에서 |
유지보수 용이 | Conti 생성 로직 수정 시 DTO 안에서만 변경 가능 |
테스트 분리 가능 | toEntity() 단독 테스트 가능 |
패턴 | 역할 | 예시 위치 |
---|---|---|
toEntity() | DTO → Entity 변환 (초기 생성) | CreateRequest.toEntity(...) |
from() | Entity → DTO 변환 (조회 응답) | Response.from(entity) |
update() | Entity 내부 상태 변경 | entity.update(...) |