我有以下类:
public class A{
List<AA> aaList;
public A(List<AA> aaList){
this.aaList = aaList;
}
//getters and setters + default constructor
public class AA {
String aaString;
public AA(String aaString){
this.aaString = aaString;
}
//getters and setters + default constructor
}
}
我想拥有同一类的两个对象,假设:
A a = new A(Arrays.asList(new A.AA(null)));
A a2 = new A(Arrays.asList(new A.AA("test")));
,当我将a
映射到a2
时,a2
应该保留test
,因为a
具有null
。
如何使用Orika
配置?
我尝试了类似的东西:
mapperFactory.classMap(A.AA.class, A.AA.class)
.mapNulls(false)
.byDefault()
.register();
mapperFactory.classMap(A.class, A.class)
.mapNulls(false)
.customize(new CustomMapper<A, A>() {
@Override public void mapAtoB(A a, A a2,
MappingContext context) {
map(a.getAAList(), a2.getAAList());
}
})
.byDefault()
.register();
预先感谢
这是一个修改的代码段,对我有用:
mapperFactory.classMap(A.class, A.class)
.mapNulls(false)
.customize(new CustomMapper<A, A>() {
@Override
public void mapAtoB(A a, A a2, MappingContext context) {
// 1. Returns new list with not null
List<A.AA> a1List = a.getAaList().stream()
.filter(a1 -> a1.getAaString() != null)
.collect(Collectors.toList());
// 2. Merges all the elements from 'a2' list into 'a' list
a1List.addAll(a2.getAaList());
// 3. Sets the list with merged elements into the 'a2'
a2.setAaList(a1List);
}
})
.register();
请注意,应删除.byDefault()
,以使自定义映射器正常工作。