Mar*_*llo 1 java mapping mapstruct
我有这些豆子:
public class Company {
private String name;
private List<Address> addresses;
...some other fields...
}
public class Address {
private String street;
private String city;
private boolean deleted;
...some other fields...
}
Run Code Online (Sandbox Code Playgroud)
我还有一些用于这些豆子的 DTO
public class CompanyDto {
private String name;
private List<AddressDto> addresses;
...some other fields...
}
public class AddressDto {
private String street;
private String city;
...some other fields...
}
Run Code Online (Sandbox Code Playgroud)
(请注意,AddressDto 类缺少该deleted字段)
我正在使用 Mapstruct 将这些 bean 映射到它们的 DTO。映射器是这样的:
@Mapper
public interface CompanyMapper {
CompanyDto companyToCompanyDto(Company company);
List<AddressDto> ListAddressToListAddressDto(List<Address> addresses);
}
Run Code Online (Sandbox Code Playgroud)
现在,在映射中我想忽略deleted字段为 的Address 实例true。我有办法实现这一目标吗?
小智 6
I'm not sure if you can get it out of the box from MapStruct features.
From Documentation:
The generated code will contain a loop which iterates over the source collection, converts each element and puts it into the target collection. - https://mapstruct.org/documentation/stable/reference/html/#mapping-collections
I want to ignore the Address instances whose deleted field is true - to do it you need your own implementation of mapping this collection.
Below an example of CompanyMapper
@Mapper
public interface CompanyMapper {
CompanyDto companyToCompanyDto(Company company);
AddressDto addressToAddressDto(Address address);
default List<AddressDto> addressListToAddressDtoList(List<Address> list) {
return list.stream()
.filter(address -> !address.isDeleted())
.map(this::addressToAddressDto)
.collect(Collectors.toList());
}
}
Run Code Online (Sandbox Code Playgroud)