【问题标题】:Orika no mapping of null elements in listOrika没有映射列表中的空元素
【发布时间】:2017-11-03 14:47:39
【问题描述】:

我有以下课程:

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();

提前致谢

【问题讨论】:

  • 如何将a 映射到a2?我的意思是你试过了吗?我对此感到困惑。

标签: java null mapper orika


【解决方案1】:

这是对我有用的修改后的代码 sn-p:

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

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 2013-12-20
    • 2017-03-22
    • 2018-02-19
    相关资源
    最近更新 更多