mapstruct - 列表<String> 到列表<Object>

mapstruct - List<String> to List<Object>

我的 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
    }
}