0

I have a spring application that uses the modelmapper to convert between the entity and the DTO objects. I have a String in the DTO that represents a ZonedDateTime object in the Entity. I have written the following snippet in the SpringAppConfiguration

    @Bean
public ModelMapper contactModelMapper() {

    Converter<String, ZonedDateTime> toZonedDateTimeString = new AbstractConverter<String, ZonedDateTime>() {
        @Override
        public ZonedDateTime convert(String source) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime datel = LocalDateTime.parse(source, formatter);
            ZonedDateTime result = datel.atZone(ZoneId.systemDefault());
            return result;
        }
    };
    Converter<ZonedDateTime, String> toStringZonedDateTime = new AbstractConverter<ZonedDateTime, String>() {
        @Override
        public String convert(ZonedDateTime source) {
            String result = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(source);
            return result;
        }
    };

    PropertyMap<Contact, ContactDTO> contactDTOmap = new PropertyMap<Contact, ContactDTO>() {
        @Override
        protected void configure() {
            map().setTenantId(source.getTenant().getTenantId());
            //if (source.getCreatedDateTime() != null) map().setCreatedDateTime(source.getCreatedDateTime());
            //when(Conditions.isNotNull()).map(source.getCreatedDateTime(), map().getCreatedDateTime());
        }
    };

    /* this is for userDTO to BO.. */
    PropertyMap<ContactDTO, Contact> contactMap = new PropertyMap<ContactDTO, Contact>() {
        @Override
        protected void configure() {
            map().getTenant().setTenantId(source.getTenantId());
        }
    };
    ModelMapper contactModelMapper = new ModelMapper();
    contactModelMapper.addMappings(contactDTOmap);
    contactModelMapper.addMappings(contactMap);
    contactModelMapper.addConverter(toStringZonedDateTime);
    contactModelMapper.addConverter(toZonedDateTimeString);
    return contactModelMapper;
}

As you can see there are 2 converters. The one that changes from DTO string to the ZonedDateTime object in entity does not get executed at all. The one for vice versa conversion is executing properly.

I would appreciate any help, any suggessions for this.

Thanks

kavita
  • 845
  • 4
  • 14
  • 40

1 Answers1

0

I have resolved the error after a lot of reading online and experimenting. It seems the order of the addConverter calls matters. I had added the converter for dto to entity conversion after the converter for entity to dto conversion. As soon as the order was put right the code started working. Posting this so that it helps someone as the documentation for modelmapper is very choppy..

kavita
  • 845
  • 4
  • 14
  • 40