映射列表在Dozer中列出

时间:2016-05-17 18:22:33

标签: java xml list mapping dozer

2016-05-17 14:14:18 kafka-binder- DEBUG KafkaMessageChannelBinder$ReceivingHandler:115 - org.springframework.cloud.stream.binder.kafka.KafkaMessageChannelBinder$ReceivingHandler@5044f552 received message: GenericMessage [payload=byte[287], headers={kafka_offset=62, kafka_messageKey=null, kafka_topic=error.redeemed.poc, kafka_partitionId=0, kafka_nextOffset=63}] - {}

CustomerData.java

List<CustomerData> mapAddress(List<Address> addressList){

   List<Customer> customerData = new ArrayList<Customer>();

   if( CollectionUtils.isNotEmpty( addressList ) ){
        for( Address address : addressList )
        {
            customerData.add( this.dozerBeanMapper.map( address, Customer.class ) );
        }
   }
   return customerData;
}

Address.java

Has instance field 'address' of type String

目前我正在使用for循环来映射地址与Customer的每个对象,如何直接将 addressList 映射到 customerData (列表到列表)而不循环。有人可以帮我修改这个逻辑的xml文件。

2 个答案:

答案 0 :(得分:1)

据我记得,没有可能将集合映射到Dozer中的集合。你需要迭代它。看看这个封闭的问题和原因:https://github.com/DozerMapper/dozer/issues/5

你可以做些什么来减轻痛苦,可以使用Java 8(如果可以的话)或Guava来处理映射的更多声明性方法。

Java 8示例:

<FROM, TO> List<TO> mapList(List<FROM> fromList, final Class<TO> toClass) {
    return fromList
            .stream()
            .map(from -> this.dozerBeanMapper.map(from, toClass))
            .collect(Collectors.toList());
}

番石榴示例:

<FROM, TO> List<TO> mapList(List<FROM> fromList, final Class<TO> toClass) {
    return Lists.transform(fromList, new Function<FROM, TO>() {
        @Override
        public TO apply(FROM from) {
            return this.dozerBeanMapper(from, toClass);
        }
    });
}

答案 1 :(得分:0)

嗨,我认为这可能有用,谢谢@gmaslowski的想法:

/**
 * @param <T>
 * @param <V>
 * @param fromList list source objects
 * @param toClass target class objects
 * @param mapperId map-id in to dozer-mapping file 
 * @return list of toClass mapped 
 */
public <T, V> List<V> mapList(List<T> fromList, Class<V> toClass, String mapperId) {
    return fromList.stream().map(from -> {
        try {
            return this.dozerBean.getObject().map(from, toClass, mapperId);
        } catch (Exception e) {
            log.error("Error Dozer Mapping Objects {}", e.getMessage());
        }
        return null;
    }).collect(Collectors.toList());
}