简体   繁体   中英

Orika - list to list conversion

This is probably an easy one, but I cant find it in the docs. I have a person class

class BasicPerson {
   private String name;
   private int age;
   private Date birthDate;
   // getters/setters omitted
}

and a list of it

ArrayList<Person>

I want to change them to change them to

ArrayList<PersonDTO>

but with out an explicit loop. Is there a way to use MapperFacade.map for a list to list one line conversion ?

It has this functionality built-in. Did you tried using the method

List<D> ma.glasnost.orika.impl.ConfigurableMapper.mapAsList(Iterable<S> source, Class<D> destinationClass) ?

I tried to find a updated version of the Javadoc, but here is one of the 1.3.5. The current version is 1.4.5. MapperFacade Class

If you use the MapperFacade interface, Orika can perform the mapping multiple times on the collection:

final MapperFacade mapperFacade = mapperFactory.getMapperFacade();
final List<Person> people = // Get the person instances
final List<PersonDto> personDtos = mapperFacade.mapAsList(people, PersonDto.class);

On the other hand, if you use the BoundMapperFacade interface, it doesn't contain such a convenience method.

And lastly, if you choose to use the ConfigurableMapper approach, it also includes a mapAsList method which in fact delegates to the MapperFacade.mapAsList method.

package com.miya.takeaway.common.util.orika;

import com.miya.takeaway.common.util.orika.converter.ConverterHelper;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.converter.ConverterFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import ma.glasnost.orika.metadata.ClassMapBuilder;
import org.apache.commons.collections4.CollectionUtils;

import java.util.Collections;
import java.util.List;

public class OrikaUtils {

    private static MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();


    public static <T> List<T> map(List<?> objects, Class<T> target) {
        if (CollectionUtils.isEmpty(objects)) {
            return Collections.EMPTY_LIST;
        }
        return mapperFactory.getMapperFacade().mapAsList(objects.toArray(), target);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM