如何解决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...
}
我也有一些用于这些 bean 的 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...
}
(请注意 AddressDto 类缺少 deleted
字段)
我正在使用 Mapstruct 将这些 bean 映射到它们的 DTO。映射器是这样的:
@Mapper
public interface CompanyMapper {
CompanyDto companyToCompanyDto(Company company);
List<AddressDto> ListAddresstoListAddressDto(List<Address> addresses);
}
现在,在映射中,我想忽略 deleted
字段为 true
的 Address 实例。有没有办法让我实现这一目标?
解决方法
我不确定您是否可以从 MapStruct 功能中立即使用它。
来自文档:
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
- 为此,您需要自己实现映射此集合。
下面是一个 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());
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。