[英]MapStruct: Fields from Different Entities mapping to Same Entity Different fields
我有A,B和C類.A類有三個變量,它根據B類和C類的不同字段填充。當我使用mapper填充對象時,只保留最后使用的映射器值。 如何確保填充所有值。 我使用MapStruct映射器(版本1.2.0)與Spring Boot版本2.0.3
Sample code below:
Class A{
String a;
String b;
String c;
}
Class B{
String b1;
}
Class C{
String c1;
}
public interface AtoCmapper{
@Mappings({
@Mapping(target="c", source="source.c1")
})
A CtoA(C source);
@Mappings({
@Mapping(target="c1", source="source.c")
})
C AtoC(A source);
}
public interface AtoBmapper{
@Mappings({
@Mapping(target="b", source="source.b1")
})
A BtoA(B source);
@Mappings({
@Mapping(target="b1", source="source.b")
})
B AtoB(A source);
}
Class DAO{
@Autowired
AtoBmapper aToBMapper;
@Autowired
AtoCmapper aToCMapper;
public void testMapping(){
A aObject = new A();
aObject = aToBMapper(bObject); // Assume bObject is object to Type B and it is initialized properly
aObject = aToCMapper(cObject); // Assume cObject is object to Type B and it is initialized properly
}
//Now when I call testMapping() resulting A object only has value set for variable c, value of b is lost.
How can I make sure that Values from B and C are set properly to Class A
}
MapStruct可以更新現有實例 ! 為此,請使用具有類型A
的第二個@MappingTarget
注釋參數的變體引入新的映射方法(或替換舊映射方法)(在這種情況下,可以用void
替換返回類型):
// In AtoBmapper
@Mappings(...)
void updateAFromB(B source, @MappingTarget A target);
// In AtoCmapper
@Mappings(...)
void updateAFromC(C source, @MappingTarget A target);
然后你可以寫:
A aObject = new A();
aToBMapper.updateAFromB(bObject, aObject);
aToCMapper.updateAFromC(cObject, aObject);
// now aObject should contain the cumulated data from b and c
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.