我的 DTO 中有一个字符串列表,我想将其映射到对象列表中,在映射器中我使用该服务通过该字符串获取对象,但出现以下错误
Can't map property "java.util.List<java.lang.String> customers" to "java.util.List<com.softilys.soyouz.domain.Customer> customers".
Consider to declare/implement a mapping method: "java.util.List<com.softilys.soyouz.domain.Customer> map(java.util.List<java.lang.String> 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 不知道如何从 List<String>
进行映射。进入List<Customer>
。反过来也可以,因为您已经定义了
default String fromCustomer(Customer customer) {
return customer == null ? null : customer.getCode();
}
要解决此问题,您还需要定义相反的内容。
@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();
}
default Customer fromStringToCustomer(String customerId) {
// Implement your custom mapping logic here
}
}
关于java - mapstruct - 列表<字符串> 到列表<对象>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59215370/