Java 使用modelmapper将列表大小映射到int字段
我是modelmapper的新手。在我的SpringBoot项目中,我有部门和员工课程。系班有员工名单。我想使用ModelMapper创建具有staffCount字段的DepartmentDTO。我在下面的课程中增加了部门和部门。如何实现这种映射 系级Java 使用modelmapper将列表大小映射到int字段,java,spring-boot,modelmapper,Java,Spring Boot,Modelmapper,我是modelmapper的新手。在我的SpringBoot项目中,我有部门和员工课程。系班有员工名单。我想使用ModelMapper创建具有staffCount字段的DepartmentDTO。我在下面的课程中增加了部门和部门。如何实现这种映射 系级 public class Department { private Long id; private String departmentName; private Set<Staff> staffList =
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
}
public class DepartmentDTO {
private Long id;
private String departmentName;
private int staffCount = 0;
public DepartmentDTO(String departmentName) {
this.departmentName = departmentName;
}
// getters and setters
}
我从中找到了解决办法。我已经创建了DepartmentStaffListToStaffCountConverter类。并在向SpringBootApplication配置文件上的modelmapper实例添加映射时使用它 部门STAFFListToStaffCountConverter
public class DepartmentStaffListToStaffCountConverter extends AbstractConverter<Set<Staff>, Integer> {
@Override
protected Integer convert(Set<Staff> staffList) {
if(staffList != null) {
return staffList.size();
} else {
return 0;
}
}
}
公共类DepartmentStaffListToStaffCountConverter扩展了AbstractConverter{
@凌驾
受保护的整数转换(Set staffList){
如果(staffList!=null){
返回staffList.size();
}否则{
返回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;
}
}
@springboot应用程序
公共类springboot应用程序{
公共静态void main(字符串[]args){
run(springbootplication.class,args);
}
@豆子
公共模型映射器getModelMapper(){
ModelMapper ModelMapper=新的ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
modelMapper.typeMap(Department.class,DepartmentDTO.class)
.addMappings(新属性映射(){
@凌驾
受保护的void configure(){
使用(new DepartmentStaffListToStaffCountConverter()).map(source.getStaffList(),destination.getStaffCount());
}
});
返回模型映射器;
}
}