我是模型映射器的新手。我的 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/