我在DTO中有一个字符串列表,我想将其映射到对象列表中,在映射器中,我使用该服务通过此字符串获取对象,但是我遇到以下错误
无法将属性“ java.util.List客户”映射到“ java.util.List客户”。
考虑声明/实现映射方法:“ java.util.Listmap(java.util.List value)“。
public class FirstDomain implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private String id;
private String description;
private List<Customer> customers;
}
public class FirstDomainDTO {
private String id;
private String description;
private List<String> customers;
}
@Mapper(uses = { CustomerService.class })
public interface FirstDomainMapper extends EntityMapper<FirstDomainDTO, FirstDomain> {
@Mapping(source = "customers", target = "customers")
FirstDomainDTO toDto(FirstDomain firstDomain);
@Mapping(source = "customers", target = "customers")
FirstDomain toEntity(FirstDomainDTO firstDomainDTO);
default String fromCustomer(Customer customer) {
return customer == null ? null : customer.getCode();
}
}
通用类型不固定化(但是将来会使用),因此MapStruct
无法理解如何映射两个列表。您唯一的选择是使用自定义映射方法。
@Named("CustomersMapping")
public class CustomersMapping {
@Named("StringToCustomer")
public List<Customer> toCustomers(final List<String> customers) {
...
}
@Named("CustomerToString")
public List<String> toStrings(final List<Customer> customers) {
...
}
}
和
@Mapper(uses = { CustomerMapping.class })
public interface FirstDomainMapper extends EntityMapper<FirstDomainDTO, FirstDomain> {
@Mapping(source = "customers", target = "customers", qualifiedByName = { "CustomersMapping", "CustomerToString" })
FirstDomainDTO toDto(final FirstDomain firstDomain);
@Mapping(source = "customers", target = "customers", qualifiedByName = { "CustomersMapping", "StringToCustomer" })
FirstDomain toEntity(final FirstDomainDTO firstDomainDTO);
}