How to map java.time.LocalDate field with Orika?

7k views Asked by At

This occurs because LocalDate is not a JavaBean (it has no zero-arg constructor)

To fix this, you need to create a LocalDateConverter :

public class LocalDateConverter extends BidirectionalConverter<LocalDate, LocalDate> {

  @Override
  public LocalDate convertTo(LocalDate source, Type<LocalDate> destinationType) {
    return (source);
  }

  @Override
  public LocalDate convertFrom(LocalDate source, Type<LocalDate> destinationType) {
    return (source);
  }

}

and then register it adding this line :

mapperFactory.getConverterFactory().registerConverter(new LocalDateConverter());

As a shorcut, you can instead register the provided "PassThroughConverter" as suggested by Adam Michalik so Orika doesn't try to instanciate a new "LocalDate" :

mapperFactory.getConverterFactory().registerConverter(new PassThroughConverter(LocalDate.class));
3

There are 3 answers

0
Tristan On BEST ANSWER

This occurs because LocalDate is not a JavaBean (it has no zero-arg constructor)

To fix this, you need to create a LocalDateConverter :

public class LocalDateConverter extends BidirectionalConverter<LocalDate, LocalDate> {

  @Override
  public LocalDate convertTo(LocalDate source, Type<LocalDate> destinationType) {
    return (LocalDate.from(source));
  }

  @Override
  public LocalDate convertFrom(LocalDate source, Type<LocalDate> destinationType) {
    return (LocalDate.from(source));
  }

}

and then register it adding this line :

mapperFactory.getConverterFactory().registerConverter(new LocalDateConverter());
1
Karan Mehta On

OrikaMapper has fixed this in the 1.5.1 release. You can upgrade your dependency to 1.5.1 and it should be added there automatically. No need of adding a converter. Here are the release notes for 1.5.1: https://github.com/orika-mapper/orika/issues/179

PR for the fix: https://github.com/orika-mapper/orika/pull/178

        <dependency>
            <groupId>ma.glasnost.orika</groupId>
            <artifactId>orika-core</artifactId>
            <version>1.5.1</version>
        </dependency>
3
Adam Michalik On

Even better, since LocalDate is immutable, there's no harm in using the same object in the source and target beans. You can configure your MapperFactory as follows:

mapperFactory.getConverterFactory().registerConverter(new PassThroughConverter(LocalDate.class));