隐藏mapstruct中未映射的属性

时间:2019-02-26 15:45:08

标签: mapstruct

我正在使用DTO对象从spring rest控制器中的@RequestBody中检索信息,并在json响应中使用了相同的DTO对象。 我想从响应中完全隐藏一些字段。

我尝试了@BeanMapping(ignoreByDefault = true),该未映射的属性返回null,但我的问题是:

有没有一种方法可以根据不同的映射方法完全隐藏未映射的属性

示例

public Class Order {
private Long id;
private String name;
private String otherField;
}

public Class OrderDto {
private Long id;
private String name;
private String otherFieldA
private String otherFieldB;
}

@Mapper
public interface OrderMapper

//..

@Mappings({
  @Mapping(target = "id", source ="id"),
  @Mapping(target = "name", source ="name"),
  @Mapping(target = "otherFieldA", source ="otherField")
  })
@BeanMapping(ignoreByDefault = true)
OrderDto fieldAOnlyOrderToOrderDtoMapper(Order order);


@Mappings({
  @Mapping(target = "id", source ="id"),
  @Mapping(target = "name", source ="name"),
  @Mapping(target = "otherFieldB", source ="otherField")
  })
@BeanMapping(ignoreByDefault = true)
OrderDto fieldBOnlyOrderToOrderDtoMapper(Order order);

}
  1. 因此调用第一个映射器[
  

fieldAOnlyOrderToOrderDtoMapper

将返回一个 OrderDto 对象,该对象没有名为(otherFieldB)的属性

  1. 以及第二个映射器的调用
  

fieldBOnlyOrderToOrderDtoMapper

将返回一个 OrderDto 对象,该对象没有名为(otherFiledA)的字段

1 个答案:

答案 0 :(得分:0)

您想忽略特定字段的IIUC。就是这样:

@Mapper
public interface OrderMapper

//..

@Mapping(target = "otherFieldA", source ="otherField")
@Mapping(target = "otherFieldB", ignore=true")
OrderDto fieldAOnlyOrderToOrderDtoMapper(Order order);


@Mapping(target = "otherFieldA", ignore=true)
@Mapping(target = "otherFieldB", source ="otherField")
OrderDto fieldBOnlyOrderToOrderDtoMapper(Order order);

}