How can I configure mapstruct mapper to check for empty not only for null when converting String to Long.
if ( entityOld.getNumber() != null ) {
entityNew.setNumber( Long.parseLong( entityOld.getNumber() ) );
}
the exception that I get is:
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[na:1.8.0_131]
at java.lang.Long.parseLong(Long.java:601) ~[na:1.8.0_131]
So basically if a string is empty I want that the to be considered as having the value "0".
Add a hand-written mapper with a custom mapping method and register this mapper via @Mapper#uses():
public class MyStringLongMapper {
public Long stringToLong(String string) {
return string != null && !string.isEmpty() ? Long.parseLong( string ) : null;
}
}
This hand-written method will take precedence over the built-in conversion from String to Long.
One solution, not too elegant, is to add expression for each field conversion
@Mapping(
target = "newField",
expression = "java(Long.parseLong(oldEntity.oldField().isEmpty() ? \"0\" : oldEntity.oldField()))")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With