2017-06-02 82 views
6

Mam następujące klasy:Orika bez odwzorowywania elementów null na liście

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 
    } 
} 

I chcę mieć dwa obiekty tej samej klasy, powiedzmy:

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

i kiedy map a do a2, a2 powinno pozostać test, ponieważ a ma null.

Jak mogę skonfigurować to z Orika?

Próbowałem coś takiego:

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

Dzięki z góry

+0

Jak mapować 'A' do' a2'? Próbowałeś? Jestem zdezorientowany. – Zico

Odpowiedz

0

Oto zmodyfikowany fragment kodu, który pracował dla mnie:

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

Uwaga, że ​​.byDefault() powinien zostać usunięty aby niestandardowy program odwzorowujący działał poprawnie.