Model Mapper

Overview

ModelMapper is an intelligent, refactoring safe object mapping library that automatically maps objects to each other. It uses a convention based approach.

Github: https://github.com/gitorko/project85

Model Mapper

Methods demonstrating how to use model mapper

  1package com.demo.project85;
  2
  3import java.util.ArrayList;
  4import java.util.List;
  5
  6import lombok.AllArgsConstructor;
  7import lombok.Builder;
  8import lombok.Data;
  9import lombok.NoArgsConstructor;
 10import lombok.extern.slf4j.Slf4j;
 11import org.junit.jupiter.api.Assertions;
 12import org.junit.jupiter.api.Test;
 13import org.modelmapper.Converter;
 14import org.modelmapper.ModelMapper;
 15import org.modelmapper.PropertyMap;
 16import org.modelmapper.TypeMap;
 17
 18@Slf4j
 19public class ModelMapperTest {
 20
 21    @Test
 22    public void test_inlineCall() {
 23        Person person = getPerson();
 24        ModelMapper modelMapper = new ModelMapper();
 25        TypeMap<Person, PersonView> typeMap = modelMapper.createTypeMap(Person.class, PersonView.class);
 26        typeMap.addMappings(mapper -> {
 27            mapper.map(Person::getFirstName, PersonView::setFirstName);
 28            mapper.map(Person::getFamilyName, PersonView::setLastName);
 29        });
 30        PersonView personView = modelMapper.map(person, PersonView.class);
 31        log.info("personView: {}", personView);
 32        Assertions.assertEquals(personView.getFirstName(), person.getFirstName());
 33        Assertions.assertEquals(personView.getLastName(), person.getFamilyName());
 34    }
 35
 36    @Test
 37    public void test_directCall() {
 38        Person person = getPerson();
 39        ModelMapper modelMapper = new ModelMapper();
 40        modelMapper.addMappings(personMap);
 41        PersonView personView = modelMapper.map(person, PersonView.class);
 42        log.info("personView: {}", personView);
 43        Assertions.assertEquals(personView.getFirstName(), person.getFirstName());
 44        Assertions.assertEquals(personView.getLastName(), person.getFamilyName().toUpperCase());
 45    }
 46
 47    @Test
 48    public void test_directCallJava8() {
 49        Person person = getPerson();
 50        ModelMapper modelMapper = new ModelMapper();
 51        PersonView personView = modelMapper
 52                .typeMap(Person.class, PersonView.class)
 53                .addMappings(mapper -> {
 54                    mapper.using(toUppercase)
 55                        .map(src -> src.getFamilyName(), PersonView::setLastName);
 56                    mapper.using(workStatusConvertor)
 57                            .map(src -> src.getWorkStatus(), PersonView::setWorkStatusName);
 58                    mapper.map(Person::getAge, PersonView::setAgeStr);
 59                })
 60                .map(person);
 61        log.info("personView: {}", personView);
 62        Assertions.assertEquals(personView.getFirstName(), person.getFirstName());
 63        Assertions.assertEquals(personView.getLastName(), person.getFamilyName().toUpperCase());
 64        Assertions.assertEquals(personView.getAgeStr(), String.valueOf(person.getAge()));
 65    }
 66
 67    @Test
 68    public void test_genericHelperClass() {
 69        Person person = getPerson();
 70        MapperHelper<Person, PersonView> entityMapperHelper = new MapperHelper<>(Person.class, PersonView.class);
 71        entityMapperHelper.mapper.typeMap(Person.class, PersonView.class)
 72                .addMappings(mapper -> {
 73                    mapper.using(toUppercase)
 74                            .map(src -> src.getFamilyName(), PersonView::setLastName);
 75                    mapper.using(workStatusConvertor)
 76                            .map(src -> src.getWorkStatus(), PersonView::setWorkStatusName);
 77                    mapper.map(Person::getAge, PersonView::setAgeStr);
 78                });
 79        PersonView personView = entityMapperHelper.toModel(person);
 80        log.info("personView: {}", personView);
 81        Assertions.assertEquals(personView.getFirstName(), person.getFirstName());
 82    }
 83
 84    @Test
 85    public void test_listConvertGenericHelperClass() {
 86        List<Person> personList = getListOfPersons();
 87        MapperHelper<Person,PersonView> entityMapperHelper = new MapperHelper<>(Person.class, PersonView.class);
 88        List<PersonView> personViewList = entityMapperHelper.toListModel(personList);
 89        log.info("personView: {}", personViewList);
 90        Assertions.assertEquals(personViewList.size(), personList.size());
 91    }
 92
 93    PropertyMap<Person, PersonView> personMap = new PropertyMap<>() {
 94        protected void configure() {
 95            using(toUppercase).map().setLastName(source.getFamilyName());
 96        }
 97    };
 98
 99    Converter<String, String> toUppercase =
100            context -> context.getSource() == null ? null : context.getSource().toUpperCase();
101
102    Converter<WorkStatus, String> workStatusConvertor =
103            context -> context.getSource() == null ? null : context.getSource().getStatus();
104
105    public static List<Person> getListOfPersons() {
106        List<Person> personList = new ArrayList<>();
107        personList.add(Person.builder()
108                .firstName("luke")
109                .familyName("skywalker")
110                .age(30)
111                .workStatus(WorkStatus.EMPLOYEED)
112                .build());
113        personList.add(Person.builder()
114                .firstName("han")
115                .familyName("solo")
116                .age(35)
117                .workStatus(WorkStatus.EMPLOYEED)
118                .build());
119        return personList;
120    }
121
122    public static Person getPerson() {
123        return Person.builder()
124                .firstName("luke")
125                .familyName("skywalker")
126                .workStatus(WorkStatus.EMPLOYEED)
127                .age(30)
128                .build();
129    }
130}
131
132@Data
133@Builder
134@NoArgsConstructor
135@AllArgsConstructor
136class Person {
137    String firstName;
138    String familyName;
139    WorkStatus workStatus;
140    int age;
141}
142
143enum WorkStatus {
144    EMPLOYEED("Employeed"),
145    UN_EMPLOYEED("Unemployeed");
146
147    String status;
148    WorkStatus(String status) {
149        this.status = status;
150    }
151
152    public String getStatus() {
153        return status;
154    }
155}
156
157@Data
158@Builder
159@NoArgsConstructor
160@AllArgsConstructor
161class PersonView {
162    String firstName;
163    String lastName;
164    WorkStatus workStatus;
165    String workStatusName;
166    String ageStr;
167}
 1package com.demo.project85;
 2
 3import java.util.List;
 4import java.util.stream.Collectors;
 5
 6import org.modelmapper.ModelMapper;
 7import org.springframework.data.domain.Page;
 8
 9public class MapperHelper<E, M> {
10    public MapperHelper(Class<E> entityType, Class<M> modelType) {
11        this.entityType = entityType;
12        this.modelType = modelType;
13        this.mapper = new ModelMapper();
14    }
15
16    public E toEntity(M model) {
17        return mapper.map(model, entityType);
18    }
19
20    public M toModel(E entity) {
21        return mapper.map(entity, modelType);
22    }
23
24    public Page<M> toPagedModel(Page<E> entities) {
25        return entities.map(this::toModel);
26    }
27
28    public List<M> toListModel(List<E> source) {
29        return source
30                .stream()
31                .map(this::toModel)
32                .collect(Collectors.toList());
33    }
34
35    Class<E> entityType;
36    Class<M> modelType;
37    ModelMapper mapper;
38}

References

http://modelmapper.org/

comments powered by Disqus