본문 바로가기
Spring

[Spring] mapStruct에서 LocalDateTime을 epoch Milli로 변경하는 방법

by Apère 2023. 3. 24.
반응형
@Mapper(componentModel = "spring")
public interface TestMapper extends EntityMapper<TestDTO, Test> {
    TestMapper MAPPER = Mappers.getMapper(TestMapper.class);

    default Long map(LocalDateTime localDateTime) {
        return localDateTime != null ? localDateTime.toInstant(ZoneOffset.of("+09:00")).toEpochMilli() : null;
    }

    @Override
    @Mappings({
        @Mapping(source = "insertDt", target = "insertMilli", qualifiedByName = "toLong"),
        @Mapping(source = "updateDt", target = "updateMilli", qualifiedByName = "toLong")
        
    })
    TestDTO toDto(Test test);

    @Named("toLong")
    default Long toLong(LocalDateTime localDateTime) {
        return map(localDateTime);
    }

}

mapStruct에서 qualifiedByName을 이용하여 아래처럼 LocalDateTime을 epoch Milli 로 변경할수 있습니다

@Mapper(componentModel = "spring")
public interface TestMapper extends EntityMapper<TestDTO, Test> {
    TestMapper MAPPER = Mappers.getMapper(TestMapper.class);

    default Long map(LocalDateTime localDateTime) {
        return localDateTime != null ? localDateTime.toInstant(ZoneOffset.of("+09:00")).toEpochMilli() : null;
    }

    @Override
    @Mapping(source = "insertDt", target = "insertMilli", qualifiedByName = "toLong")
    TestDTO toDto(Test test);

    @Named("toLong")
    default Long toLong(LocalDateTime localDateTime) {
        return map(localDateTime);
    }

}

만약에 여러필드를 변경하고 싶다면 아래 코드처럼 @Mappings를 이용하시면 됩니다

 

 

반응형

댓글