【问题标题】:Mapping list size to int field with modelmapper使用 modelmapper 将列表大小映射到 int 字段
【发布时间】:2020-01-29 05:30:47
【问题描述】:

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

部门类

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 类

public class DepartmentDTO {

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

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

    // getters and setters

}

【问题讨论】:

    标签: java spring-boot modelmapper


    【解决方案1】:

    我从this post 找到了解决方案。我创建了 DepartmentStaffListToStaffCountConverter 类。并在 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;
            }
        }
    }
    

    SpringBootApplication 文件

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

    【讨论】:

      猜你喜欢
      • 2017-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      • 2018-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多