Search code examples
javaspring-bootmodelmapper

Mapping list size to int field with modelmapper


I am new to modelmapper. I have Department and Staff classes in my SpringBoot project. Department class has list of staffs. Using ModelMapper I want to create DepartmentDTO that has staffCount field. I have added Department and DepartmentDTO classes below. How to achive this mapping?

Department class

public class Department {

    private Long id;
    private String departmentName;
    private Set<Staff> staffList = new HashSet<>();


    public Department(String departmentName) {
        super();
        this.departmentName = departmentName;
    }

    // getters and setters
} 

DepartmentDTO class

public class DepartmentDTO {

    private Long id;
    private String departmentName;
    private int staffCount = 0;

    public DepartmentDTO(String departmentName) {
        this.departmentName = departmentName;
    }

    // getters and setters

}

Solution

  • I have found solution from this post. I have created DepartmentStaffListToStaffCountConverter class. And used it when adding mappings to modelmapper instance on SpringBootApplication configuration file.

    DepartmentStaffListToStaffCountConverter

    public class DepartmentStaffListToStaffCountConverter extends AbstractConverter<Set<Staff>, Integer> {
    
        @Override
        protected Integer convert(Set<Staff> staffList) {
            if(staffList != null) {
                return staffList.size();
            } else {
                return 0;
            }
        }
    }
    

    SpringBootApplication file

    @SpringBootApplication
    public class SpringBootApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringBootApplication.class, args);
        }
    
        @Bean
        public ModelMapper getModelMapper() {
            ModelMapper modelMapper = new ModelMapper();
            modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
            modelMapper.typeMap(Department.class, DepartmentDTO.class)
                       .addMappings(new PropertyMap<Department, DepartmentDTO>() {
                @Override
                protected void configure() {
                    using(new DepartmentStaffListToStaffCountConverter()).map(source.getStaffList(), destination.getStaffCount());
                }
            });
            return modelMapper;
        }
    }