Search code examples
javaspringspring-bootmodelmapper

Java ModelMapper map an object in an object


I have the following DTO and VO:

VO

public class ProjectVO {
    private Date fechaInicio;
    private Date fechaFin;
}

DTO

public class ProjectDTO {
   private String fechaInicio;
   private String fechaFin;
}

And the following converter to convert the strings to dates:

Converter<String, Date> dateConverter = new Converter<String, Date>()
    {
        public Date convert(MappingContext<String, Date> context)
        {
            Date date;

            try {
                date = new SimpleDateFormat("dd/MM/yyyy").parse(context.getSource());
            } catch (ParseException e) {
                throw new DateFormatException();
            }

            return date;
        }
    };

modelMapper.addConverter(dateConverter);

If I convert a single String to a date using modelmapper it'll work perfectly with this converter.

But now I need to convert my ProjectDTO object to a ProjectVO one and I am getting an error saying that it cannot convert a String to a Date. I suspect this is because the Date is inside the Project object. Am I right? How can I solve this?

Thanks.


Solution

  • Okay it works like a charm and automatically detects it if I use this:

    modelMapper.createTypeMap(String.class, Date.class);
    

    and then add the custom converter I created :)