【发布时间】:2020-11-16 01:26:33
【问题描述】:
我正在尝试使用 MapStruct 将以下源类映射到目标类。
目标类:
public class Response {
private List<Customer> customer = new ArrayList<Customer>();
}
public class Customer {
private String customerId;
private List<Product> products = new ArrayList<Product>();
}
public class CustProduct {
private String CustProductId;
private String CustPdtName;
private List<productDetail> CustProductDetails = new ArrayList<productDetail>();
}
源类:
public class UserList {
protected List<User> user;
}
public class User {
protected String userId;
protected List<String> productRefId; //List of products for that particular user
}
public class ProductList {
protected List<Product> product;
}
public class Product {
protected String productId; //Reference to productRefId
protected String productName;
protected List<Details> productDetails;
}
映射器接口:
List<Customer> mapUser(List<User> user);
@Mappings({
@Mapping(target = "customerId", source = "userId”),
@Mapping(target = "products", ignore = true)
})
Customer mapUser(User user);
@Mappings({
@Mapping(target = "CustProductId", source = "productId"),
@Mapping(target = "CustPdtName", source = "productName"),
@Mapping(target = "CustProductDetails", source = "productDetails")
})
CustProduct mapUser(Product product);
我的问题是,我想将 CustProduct 与 Customer 联系起来 为此,我尝试了 AfterMapping :
default void findProducts(User user, @MappingTarget Customer customer) {
List<String> productIds = user.getproductRefId();
List<CustProduct> custProducts = new ArrayList<>();
for(int i=0; i<productIds.size();i++){
CustProduct custProduct = new CustProduct();
custProduct.setCustProductId(productIds.get(i));
//Here I want set productName and productDetails to custProduct Object(Iterating through ProductList and get from Product)
custProducts.add(custProduct);
}
}
customer.setCustProducts(custProducts);
}
有人可以帮忙填写上面的评论部分吗? 或者有没有其他选项来映射这些对象?
已编辑:我尝试了以下解决方案,但接口实现类本身发生了变化。
【问题讨论】:
标签: java spring-boot nested-lists mapstruct object-object-mapping