명확성을 위해 DTO에서 child entity 매핑하기

갓김치·2025년 1월 15일
0

Spring Boot

목록 보기
3/3

as-is

Service

    for (int i = 0; i < info.getDataList().size(); i++) {
        AmbientLightSaveDTO ambientLightDTO = info.getDataList().get(i);
        AmbientLightEntity ambientLightEntity = ambientLightEntityList.get(i);

        if (ambientLightDTO.getIosDetail() != null) {
            IosAmbientLightDetailEntity iosDetail = ambientLightDTO.getIosDetail().toEntity(ambientLightEntity);
            ambientLightEntity.setIosDetail(iosDetail);  // Builder ensures iosDetail is set in the entity.
        }
    }
        ambientLightRepository.saveAll(ambientLightEntityList);

DTO의 iosDetail 을 꺼내 서비스에서 매핑을 해줬었다

to-be

DTO.toEntity

public AmbientLightEntity toEntity(DeviceEntity deviceEntity, LocalDateTime now) {
    if (OsType.IOS.equals(deviceEntity.getOs()) && iosDetail == null) {
        throw new IllegalArgumentException("iOS 의 조도 디테일을 입력해 주세요.");
    }

    // Build AmbientLightEntity
    AmbientLightEntity entity = AmbientLightEntity.builder()
                                                   .isMobile(isMobile)
                                                   .lux(luxValue)
                                                   .obtainedAt(obtainedAt)
                                                   .createdAt(now)
                                                   .obtainedFrom(deviceEntity)
                                                   .build();

    // Only set iOS detail if the OS is iOS
    if (OsType.IOS.equals(deviceEntity.getOs())) {
        entity.setIosDetail(iosDetail.toEntity(entity));
    }

    return entity;
}

ios일 경우 toEntity 에서 바로 child entity 매핑을 해주면 더욱 명확하고 간결하다.
ios 와 android를 따로 서비스에서 처리해주지 않아 공통된 메서드를 쓸 수 있다.

profile
갈 길이 멀다

0개의 댓글