mapstruct-List <String>到List <Object>

时间:2019-12-06 14:49:32

标签: java spring dto mapstruct

我的DTO中有一个字符串列表,我想将其映射到对象列表中,在映射器中,我使用了该字符串来获取对象的服务,但是出现以下错误

  

无法将属性“ java.util.List 客户”映射到   “ java.util.List 客户”。

     

考虑声明/实现映射方法:   “ java.util.List   map(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();
    }

}

1 个答案:

答案 0 :(得分:1)

您收到的错误消息应该足以帮助您了解问题所在。在这种情况下,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
    }
}
相关问题