2014-12-09 4 views
1

Я хотел бы отобразить поле с вложенной коллекцией, используя библиотеку Орики. Мое поле в классе определяется как:Может ли Orika отображать вложенные коллекции?

private final List<List<Pojo>> list = new LinkedList<List<Pojo>>(); 

Pojo - это простой класс POJO. К сожалению, у меня есть MappingException, вызванное NullPointerException во внутренней логике Орики.

Я сделал что-то не так? Может быть, мне нужно использовать функцию Custom Mapping?

EDIT:

Вот мой код:

public class Pojo { 
private int field; 

public int getField() { 
    return field; 
} 

public void setField(final int field) { 
    this.field = field; 
} 

}

общественный класс Источник { частный окончательный список> Список = новый LinkedList>();

public List<List<Pojo>> getList() { 
    return list; 
} 

}

общественного класса назначения { частный окончательный список> listDest = новый LinkedList>();

public List<List<Pojo>> getListDest() { 
    return listDest; 
} 

}

общественного класса Main {

public static void main(final String[] args) { 

    final MapperFactory factory = new DefaultMapperFactory.Builder().build(); 

    factory.classMap(Source.class, Destination.class).field("list", "listDest").byDefault().register(); 

    final Source src = new Source(); 
    final LinkedList<Pojo> nestedList = new LinkedList<Pojo>(); 
    final Pojo pojo = new Pojo(); 
    pojo.setField(8978); 

    nestedList.add(pojo); 

    src.getList().add(nestedList); 

    final MapperFacade facade = factory.getMapperFacade(); 
    final Destination dest = facade.map(src, Destination.class); 

    System.out.println(dest.getListDest().get(0).get(0).getField()); 
} 

}

Выполнение выше результатов кода это исключение:

Exception in thread "main" ma.glasnost.orika.MappingException: Error encountered while mapping for the following inputs: 
[email protected] 
sourceClass=class com.bbh.nested.Source 
destinationClass=class com.bbh.nested.Destination 
+0

Можете ли вы показать нам, как вы настроить отображение и как вызвать Orika? –

+0

@SidiMohamed Спасибо за ваш ответ. Я прикрепил образец кода. – Viper

ответ

0

Это может потребоваться пользовательское сопоставление с помощью подгоняет если есть s много случаев, как это вы можете расширить Orika поддержать этот вариант использования

+0

Как мы можем использовать настраиваемое сопоставление, пожалуйста, помогите мне. Я новичок в области Orika. –

0

Вы можете увидеть этот пример с помощью Спецификации:

public class ShopEntity { 
    private Long id; 
    private String name; 
    private String logo; 
    private String url; 
    private ProductCategory mainCategory; 
    private Set<ShopRel> shopRels = new HashSet<>(0); 
    private Account account; 
    // Assume getter/setter 
} 

public class ProductCategory extends BaseEntity { 
    private Long id; 
    private String name; 
    // Assume getter/setter 
} 

public class ShopRel { 
    private Long id; 
    private SaleChannel saleChannel; 
    private Boolean enabled; 
    // Assume getter/setter 
} 

public class SaleChannel { 
    private Long id; 
    private String name; 
    private String image; 
    private String description; 
    private Boolean active; 
    // Assume getter/setter 
} 


public class ShopDto { 
    private Long id; 
    private String name; 
    private String logo; 
    private String url; 
    private Long mainCategory; 
    private Set<ShopRelDto> shopRelDtos = new HashSet<ShopRelDto>(); 
    // Assume getter/setter 
} 

public class ShopRelDto { 
    private Long channelId; 
    private String name; 
    private Boolean enabled; 
    // Assume getter/setter 
} 

public class MapperUtils { 
    private static final MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build(); 
    private static final MapperFacade mapper = mapperFactory.getMapperFacade(); 
    static { 
     mapperFactory.classMap(ShopEntity.class, ShopDto.class) 
      .field("mainCategory.id", "mainCategory") 
      .fieldMap("shopRels", "shopRelDtos").aElementType(ShopRel.class).bElementType(ShopRelDto.class).add() 
      .register(); 
     mapperFactory.classMap(ShopRel.class, ShopRelDto.class) 
      .field("saleChannel.id", "channelId") 
      .field("saleChannel.name", "name") 
      .field("enabled", "enabled") 
      .register(); 
    } 

    public static final void map(Object source, Object distance) { 
     mapper.map(source, distance); 
    } 

    public static final <T> T map(Object source, Class<T> destinationClass){ 
     return mapper.map(source, destinationClass); 
    } 

    public static void main(String[] args) { 
     ShopEntity shop = new ShopEntity(); 
     shop.setId(1L); 
     shop.setName("ABC"); 
     ProductCategory productCategory =new ProductCategory(); 
     productCategory.setId(10L); 
     shop.setMainCategory(productCategory); 

     Set<ShopRel> shopRels = new HashSet<>(0); 
     ShopSaleChannelRel channelRel = new ShopSaleChannelRel(); 
     channelRel.setId(1L); 
     channelRel.setEnabled(true); 
     SaleChannel saleChannel = new SaleChannel(); 
     saleChannel.setId(1L); 
     saleChannel.setName("Channel1"); 
     channelRel.setSaleChannel(saleChannel); 
     shopRels.add(channelRel); 
     shop.setShopRels(shopRels); 
     ShopDto shopDto = map(shop, ShopDto.class); 
     System.out.println(shopDto); 
    } 
} 
+0

Вы должны указать некоторые дополнительные детали в своем ответе, почему/как это исправляет исходную проблему. – Graham