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

imTachu
  • 3,759
  • 4
  • 29
  • 56
user1345883
  • 451
  • 1
  • 8
  • 24

1 Answers1

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.

Danylo Zatorsky
  • 5,856
  • 2
  • 25
  • 49