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

标签 java spring-boot modelmapper

我是模型映射器的新手。我的 SpringBoot 项目中有 Department 和 Staff 类。部门类(class)有人员名单。使用 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
} 

部门DTO类

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 类。并在 SpringBootApplication 配置文件上将映射添加到 modelmapper 实例时使用它。

部门员工列表到员工计数转换器

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

关于java - 使用 modelmapper 将列表大小映射到 int 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59955122/

相关文章:

java - 找不到亚马逊凭据方法

java - AWS, Spring 启动,Tomcat : Session replication

spring-boot - lombok 是否应该在 spring-boot-dependencies 中提供一个作用域?

mysql - 如何在Spring Boot中使用实体解决SQL语法错误?

java - Modelmapper:当源对象为空时如何应用自定义映射?

java - 模型映射器空值跳过

java - 将字符串中的英文数字替换为阿拉伯数字

java - 模式匹配时如何忽略嵌套括号?

java - ModelMapper propertyMap 与响应DTO 的对象列表

java - 即使应用程序关闭,也尝试保存复选框的状态和该复选框内的数据