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.