使用 MapStruct,我想将我的 RecipientDTO 映射到 Recipient。我希望 RecipientDTO 中的 AddressDTO 成为 Recipient.subscriptions 的每个订阅中的地址。如何使用 MapStruct 实现此目的?我的课程是这样的:
public class AddressDTO {
String street;
String city;
}
public class SubscriptionDTO {
String category;
}
public class RecipientDTO {
String name;
AddressDTO address;
List<SubscriptionDTO> subscriptions;
}
public class Address {
String street;
String city;
}
public class Subscription {
Address address;
String category;
}
public class Recipient {
String name;
List<Subscription> subscriptions;
}
我尝试为订阅指定一个单独的映射器接口。所以
@Mapper
public interface SubscriptionMapper {
SubscriptionMapper INSTANCE = Mappers.getMapper(SubscriptionMapper.class);
@Mapping(target = "address", source = "addressDTO")
Subscription toSubscription(SubscriptionDTO dto, AddressDTO addressDTO);
}
这将生成一个用于订阅的映射器。
但是当我这样做时
@Mapper(uses = SubscriptionMapper.class)
public interface RecipientMapper {
RecipientMapper INSTANCE = Mappers.getMapper(RecipientMapper.class);
Recipient toRecipient(RecipientDTO recipientDTO);
}
它不会使用来自 SubscriptionMapper 的带有额外参数的映射方法。
如果可能的话我想做这样的事情:
@Mapping(target = "subscriptions.address", source = "address")
Recipient toRecipient(RecipientDTO recipientDTO);
您需要使用@AfterMapping注释。此注释允许您在标准映射过程之后添加自定义代码。
@Mapper
public interface RecipientMapper {
RecipientMapper INSTANCE = Mappers.getMapper(RecipientMapper.class);
Recipient toRecipient(RecipientDTO recipientDTO);
@AfterMapping
default void updateAddresses(RecipientDTO recipientDTO, @MappingTarget Recipient recipient) {
if(Objects.nonNull(recipient) && !CollectionUtils.isEmpty(recipient.getSubscriptions())){
recipient.getSubscriptions().forEach(rcpt -> {
var address = recipientDTO.getAddress();
rcpt.setAddress(Address.builder().city(address.getCity()).street(address.getStreet()).build());
});
}
}
}