如何使用 mapStruct 仅映射选定的字段并返回它们作为响应。
例如:
class Location {
String street;
String unit;
int postCode;
}
public class Car {
private Location location;.
}
public class CarDto {
private Location location;
}
现在我可以使用以下方式映射它们:
@Mapper
public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );
CarDto returnObject = CarDto carToCarDto(Car car);
}
现在,returnObject
将包含具有街道、单位和邮政编码
的位置。
但是,我只想通过 returnObject.location 公开街道和 postCode
。
如何只公开那些选定的字段?
最佳答案
当您只想映射某些字段并忽略其他所有字段时,可以使用BeanMapping#ignoreByDefault
。
例如
@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);
}
通过使用@BeanMapping(ignoreByDefault = true)
,您将忽略所有属性。通过使用@Mapping
,您可以定义要映射的属性。
关于java - 如何使用mapstruct仅映射选定的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65822574/