Orika no mapping of null elements in list
Asked Answered
C

1

6

I have the following 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
    }
}

And I want to have two objects of the same class, let's say:

A a = new A(Arrays.asList(new A.AA(null)));
A a2 = new A(Arrays.asList(new A.AA("test")));

and when I map a to a2, a2 should remain test because a has a null.

How can I configure this with Orika?

I tried something like:

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

Thanks in advance

Cramped answered 2/6, 2017 at 8:54 Comment(1)
How do you map a to a2? I mean did you try? I am confused about it.Malonylurea
S
0

Here is a modified code snippet that worked for me:

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

Note, that the .byDefault() should be removed in order for the custom mapper to work properly.

Sore answered 12/6, 2017 at 19:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.