Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert empty string to Long in Mapstruct?

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".

like image 695
aurelius Avatar asked Nov 01 '25 20:11

aurelius


2 Answers

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.

like image 144
Gunnar Avatar answered Nov 04 '25 10:11

Gunnar


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()))")
like image 45
aurelius Avatar answered Nov 04 '25 11:11

aurelius