Spring boot project, using Dozer to move the LocalDateTime attribute in JPA entity to an error in the corresponding LocalDateTime attribute in the DTO
Java.lang.nosuchmethodexception:java.time.localdatetime.<init> () at Java.lang.Class.getConstructor0 ( class.java:3082) ~[na:1.8.0_51]at java.lang.Class.getDeclaredConstructor (class.java:2178) ~[na:1.8.0_51]at Org.dozer.factory.constructionstrategies$byconstructor.newinstance (constructionstrategies.java:272) ~[ Dozer-5.5.1.jar:na]
Replace the LocalDateTime in the DTO with a date and an error
Java.lang.NumberFormatException:For input string: "2015-10-17t17:55:12.091"
Workaround:
Add a custom Convert
public class localdatetimetodatedozerconverter extends dozerconverter<localdatetime, date> { public localdatetimetodatedozerconverter () { super ( Localdatetime.class, date.class); } @Override public localdatetime convertfrom (date source, localdatetime destination) { Localdatetime datetime = localdatetime.ofinstant (Source.toinstant (), ZoneId.systemDefault ( )); return datetime; } @Override public date convertto (localdatetime source, date destination) { date converttodate = date.from (Source.atzone (Zoneid.systemdefault ()). Toinstant ()); return converttodate; }}
Add an XML configuration file under the Classpath
<?xml version= "1.0" encoding= "UTF-8"? ><mappings xmlns= "Http://dozer.sourceforge.net" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance " xsi:schemalocation=" http// dozer.sourceforge.net http://dozer.sourceforge.net/ Schema/beanmapping.xsd "> <configuration> <custom-converters> <!-- these are always bi-directional --> <converter type= "Com.demo.LocalDateTimeToDateDozerConverter" > <class-a>java.time.LocalDateTime</class-a> <class-b>java.util.date</class-b> </ Converter> </custOm-converters> </configuration> </mappings>
Note that a global configuration like this can only be configured in XML, see official documentation
In fact some parts of the configuration (e.g Global configuration block) is only possible to express in XML format.
Add the following configuration to the Spring boot startup class
@Bean public Mapper Dozerbeanmapper () {list<string> mappingfileurls = lists.newarraylist ("Dozer-custom-convert. XML "); Dozerbeanmapper mapper = Getsingletondozerbeanmapper (); Mapper.setmappingfiles (Mappingfileurls); return mapper; }
Reference documents
Http://dozer.sourceforge.net/documentation/customconverter.html
Http://stackoverflow.com/questions/29550417/why-dozerconverter-is-not-working
Dozer Custom Converter--LocalDateTime to Date