0
votes

I'm using a DTO object to retrieve information from my @RequestBody in spring rest controller and using the same DTO object in json response. I want to hide some fields completely from response.

I tried the @BeanMapping(ignoreByDefault = true)which return null for unmapped properties but my question is:

Is there a way to completely hide the unmapped properties based on different mapping methods

Example

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. thus the result of calling the first mapper [

fieldAOnlyOrderToOrderDtoMapper

will return an OrderDto object that has no property named (otherFieldB)

  1. and the call for the second mapper

fieldBOnlyOrderToOrderDtoMapper

will return an OrderDto object that has no field named (otherFiledA)

1

1 Answers

0
votes

IIUC you want to ignore specific fields.. That's done like this:

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

}