使用 modelmapper 将列表大小映射到 int 字段

Mapping list size to int field with modelmapper

我是模型映射器的新手。我的 SpringBoot 项目中有 Department 和 Staff classes。部门 class 有员工列表。使用 ModelMapper 我想创建具有 staffCount 字段的 DepartmentDTO。我在下面添加了 Department 和 DepartmentDTO classes。如何实现这个映射?

部门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
} 

部门DTO class

public class DepartmentDTO {

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

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

    // getters and setters

}

我从 this post 找到了解决方案。我创建了 DepartmentStaffListToStaffCountConverter class。并在 SpringBootApplication 配置文件上向 modelmapper 实例添加映射时使用它。

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;
        }
    }
}

SpringBoot应用文件

@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;
    }
}