Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

orika

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));
like image 879
Tristan Avatar asked Jun 12 '15 14:06

Tristan


2 Answers

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>
like image 179
Karan Mehta Avatar answered Sep 27 '22 16:09

Karan Mehta


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));
like image 32
Adam Michalik Avatar answered Sep 27 '22 17:09

Adam Michalik