简体   繁体   中英

Mapstruct mapping Boolean to String

I have several Boolean fields in my model class (source). The target field in my DTO class is String . I need to map true as Y and false as N . There are more than 20 Boolean fields and right now I am using 20+ @Mapping annotation with expression option, which is overhead. There must be a simple way or solution that I am not aware. Can anyone help to simplify this?

I am using mapstruct version 1.2.0.Final

Source.java

class Source{
  private Boolean isNew;
  private Boolean anyRestriction;
  // several Boolean fields
}

Target.java

class Target{
  private String isNew;
  private String anyRestriction;
}

Helper.java

class Helper{
  public String asString(Boolean b){
    return b==null ? "N" : (b ? "Y" : "N");
  }
}

MyMapper.java

@Mapper interface MyMapper{
  @Mappings(
    @Mapping(target="isNew", expression="java(Helper.asString(s.isNew()))"
    // 20+ mapping like above, any simple way ? 
  )
  Target map(Source s);
}

If I remember correctly, you just have to provide a custom type conversion concrete method.
Let's say you're still using abstract classes for Mappers.

@Mapper
public abstract class YourMapper {
    @Mappings(...)
    public abstract Target sourceToTarget(final Source source);

    public String booleanToString(final Boolean bool) {
        return bool == null ? "N" : (bool ? "Y" : "N");
    }
}

This should be possible even with Java 8 Interface default methods.

Analogous to Map Struct Reference#Invoking Other Mappers , you can define (your Helper) class like:

public class BooleanYNMapper {

    public String asString(Boolean bool) {
        return null == bool ?
            null : (bool ? 
                "Y" : "N"
            );
    }

    public Boolean asBoolean(String bool) {
        return null == bool ?
            null : (bool.trim().toLowerCase().startsWith("y") ?
                Boolean.TRUE : Boolean.FALSE
            );
    }
}

..and then use it in (the hierarchy of) your mappers:

@Mapper(uses = BooleanYNMapper.class)
interface MyMapper{
    Target map(Source s);
    //and even this will work:
    Source mapBack(Target t);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM