LoginSignup
3
3

More than 1 year has passed since last update.

【Java】modelMapperでList<A>⇔List<B>, String⇔LocalDate, String⇔LocalDateTimeを変換する。

Posted at

参考

List<HogeEntity> → List<HogeDto> のマッピング

List<HogeEntity> entities = // DBからHogeEntityリスト取得
List<HogeDto> dtos = modelMapper.map(entities , new TypeToken<List<HogeDto>>() {}.getType());

String ⇔ LocalDate のマッピング

// String to LocalDate
mapper.addConverter(
    new AbstractConverter<String, LocalDate>() {
        @Override
        protected LocalDate convert(String source) {
            if (source == null) {
                return null;
            }
            DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            return LocalDate.parse(source, format);
        }

    }
);

// LocalDate to String
mapper.addConverter(
    new AbstractConverter<LocalDate, String>() {
        @Override
        protected String convert(LocalDate source) {
            if (source == null) {
                return null;
            }
            DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            return source.format(format);
         }
    }
);

String ⇔ LocalDateTimeのマッピング

// String to LocalDateTime
mapper.addConverter(
    new AbstractConverter<String, LocalDateTime>() {
        @Override
        protected LocalDateTime convert(String source) {
            if (source == null) {
                return null;
            }
            DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            return LocalDateTime.parse(source, format);
        }
    }
);

// LocalDateTime to String
mapper.addConverter(
    new AbstractConverter<LocalDateTime, String>() {
        @Override
        protected String convert(LocalDateTime source) {
            if (source == null) {
                return null;
            }
            DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            return source.format(format);
        }
    }
);
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3