簡體   English   中英

Orika沒有列表中的null元素的映射

[英]Orika no mapping of null elements in list

我有以下課程:

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映射到a2a2應該保持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()以使自定義映射器正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM