My DTO is having date field in String format. My entity is having date as LocalDate. Currently I am skipping it from map and then later manually explicitly setting it (Strin
If you want to convert to LocalDate
you need to create a Provider
otherwise ModelMapper
cannot instantiate LocalDate
because it doesn't have a public default constructor.
Use this configuration and it will work:
ModelMapper modelmapper = new ModelMapper();
Provider localDateProvider = new AbstractProvider() {
@Override
public LocalDate get() {
return LocalDate.now();
}
};
Converter toStringDate = new AbstractConverter() {
@Override
protected LocalDate convert(String source) {
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate localDate = LocalDate.parse(source, format);
return localDate;
}
};
modelmapper.createTypeMap(String.class, LocalDate.class);
modelmapper.addConverter(toStringDate);
modelmapper.getTypeMap(String.class, LocalDate.class).setProvider(localDateProvider);
Test output:
String dateTest = "2000-09-27";
LocalDate dateConverted = modelmapper.map(dateTest, LocalDate.class);
System.out.println(dateConverted.toString()); //Output = 2000-09-27