2017-06-02 18 views
6

Tôi có lớp sau đây:Orika không có bản đồ của các yếu tố null trong danh sách

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

Và tôi muốn có hai đối tượng của lớp đó, chúng ta hãy nói:

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

và khi tôi lập bản đồ a đến a2, a2 phải giữ nguyên testanull.

Tôi làm cách nào để định cấu hình cài đặt này với Orika?

tôi đã cố gắng một cái gì đó như:

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

Cảm ơn trước

+0

Làm cách nào để ánh xạ 'a' thành' a2'? Ý tôi là bạn đã thử? Tôi bối rối về nó. – Zico

Trả lời

0

Dưới đây là một đoạn đổi mã mà làm việc cho tôi:

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

Lưu ý, rằng .byDefault() cần được loại bỏ trong để người lập bản đồ tùy chỉnh hoạt động bình thường.

Các vấn đề liên quan