【问题标题】:Mapstruct mapping Boolean to StringMapstruct 将布尔值映射到字符串
【发布时间】:2019-07-03 18:34:36
【问题描述】:

我的模型类中有几个 Boolean 字段(来源)。我的 DTO 类中的目标字段是 String。我需要将true 映射为Y,将false 映射为N。有超过 20 个 Boolean 字段,现在我正在使用 20+ @Mapping 注释和 expression 选项,这是开销。必须有一个我不知道的简单方法或解决方案。谁能帮忙简化一下?

我正在使用mapstruct 版本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);
}

【问题讨论】:

  • 谢谢你,正是我需要的。只是想指出您的表达式需要完全限定的包名称。

标签: java string boolean mapping mapstruct


【解决方案1】:

类似于Map Struct Reference#Invoking Other Mappers,你可以定义(你的助手)类:

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

..然后在您的映射器(的层次结构)中使用它:

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

【讨论】:

    【解决方案2】:

    如果我没记错的话,你只需要提供一个自定义类型转换的具体方法。
    假设您仍在为 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");
        }
    }
    

    即使使用 Java 8 接口默认方法,这也应该是可能的。

    【讨论】:

    • 是的,您可以使用默认方法甚至界面上的默认静态方法来执行此操作
    • 两个答案都有效。我接受 @xerx593 的正确,因为我可以在其他映射器接口中重用 BooleanYNMapper。谢谢。
    猜你喜欢
    • 2019-06-09
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    • 2014-11-27
    • 2017-07-31
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    相关资源
    最近更新 更多