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);
}
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);
}
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