How do I map only selected fields with mapStructand return thenm as response.
Ex:
class Location {
String street;
String unit;
int postCode;
}
public class Car {
private Location location;.
}
public class CarDto {
private Location location;
}
Now I can map them using :
@Mapper
public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );
CarDto returnObject = CarDto carToCarDto(Car car);
}
Now, returnObject
will contain location which will have street, unit and postCode
.
But , I want to expose just the street and postCode
with returnObject.location.
How can I expose only those selected fields?
When you want to only map certain fields and ignore everything else you can use BeanMapping#ignoreByDefault
.
e.g.
@Mapper
public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );
@BeanMapping(ignoreByDefault = true)
@Mapping(target = "street", source = "location.street")
@Mapping(target = "postCode", source = "location.postCode")
CarDto carToCarDto(Car car);
}
By using @BeanMapping(ignoreByDefault = true)
you are ignoring all properties. And by using the @Mapping
you are defining which properties you want to map.