gpt4 book ai didi

java - Orika 没有映射列表中的空元素

转载 作者:搜寻专家 更新时间:2023-10-30 23:01:53 34 4
gpt4 key购买 nike

我有以下类(class):

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() 以使自定义映射器正常工作。

关于java - Orika 没有映射列表中的空元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44324716/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com