我有一个填充的对象列表,我需要从一个对象中填充更多属性。
考虑使用mapperstruct,我无法从目标列表中修改Object的先前属性。
// type for obj in list target
public class ObjectExampleA {
private String id;
private String firstAttr;
private String secondAttr;
private String thirdAttr;
}
// target list
// List<ObjectExampleA> listTarget;
// at this point considering an elements in list like this...
// {"id":1, "firstAttr":"blue", "secondAttr":"black", "thirdAttr": null}
// {"id":2, "firstAttr":"gray", "secondAttr":"red", "thirdAttr": null}
// source obj
public class ObjectExampleB {
private String thirdAttr;
}
// I need to populate all thirdAttr atribute of all elements in listTarget from ObjectExampleB.thirdAttr value
@Mapper(componentModel = "spring")
public interface ExampleMapper {
void populateThirdAttrInList(@MappingTarget List<ObjectExampleA> listTarget, ObjectExampleB objectExampleB);
}
答案 0 :(得分:1)
执行集合元素的更新并不总是那么简单。但是,可以通过更新ObjectExampleA
来以简单的方式解决您的案件。
例如
@Mapper(componentModel = "spring")
public interface ExampleMapper {
default void populateThirdAttrInList(@MappingTarget List<ObjectExampleA> listTarget, ObjectExampleB objectExampleB) {
for(ObjectExampleA exampleA: listTarget) {
populateThirdAttr(exampleA, objectExampleB);
}
}
void populateThirdAttr(@MappingTarget ObjectExampleA exampleA, ObjectExampleB exampleB);
}