模型映射器在从列表映射到另一个列表时引发错误



我映射了两个类,它们的属性都有ArrayLists和ModelMappers。我有ModelMapper 3.1.0版本和SpringBoot 2.7.4版本。在我的项目中。下面是两个模型的代码片段:VetClinic和VetCLinicDto:

public class VetClinic{
private ArrayList<Doctor> doctors;
...
}
public class VetClinic{
private ArrayList<DoctorDto> doctorDtos;
...
}

和帮助ModelMapper与映射特定字段,如集合我写的代码:

@Override
protected void mapSpecificFieldsToModelFromDto(VetClinicDto source, VetClinic destination) {
if (source.getDoctors() != null)
destination.setDoctors(source.getDoctors()
.stream().map(doctorDto -> mapper.map(doctorDto, Doctor.class))
.toList());
...
}

这个代码片段工作正常,但我试图将ArrayList更改为List,像这样:

public class VetClinic{
private List<Doctor> doctors;
...
}
public class VetClinic{
private List<DoctorDto> doctorDtos;
...
}

当ModelMapper试图将VetClinicDto映射到VetClinic时,会抛出错误:

1) Failed to instantiate instance of destination java.util.List. Ensure that java.util.List has a non-private no-argument constructor.

我已经尝试将List初始化为ArrayList。这样的:

public class VetClinic{
private List<Doctor> doctors = new ArrayList<>();
...
}
public class VetClinic{
private List<DoctorDto> doctorDtos = new ArrayList<>();
...
}

但是它不起作用。我不明白为什么ModelMapper不能将一个List映射到另一个List。

要完全回答这个问题所缺少的细节在映射器中。地图(doctorDto Doctor.class)">

但是我想看看这个链接:https://www.baeldung.com/java-copy-list-to-another

它会给你一些关于如何编写映射器来处理这个问题的想法。我还建议您考虑使用mapstruct框架来为您完成这种映射,它可以轻松地处理列表到列表的映射,并且如果对象具有相同的属性,则需要很少的配置。

@Mapper(componentModel = "spring")
public interface DoctorMapper {
List<DoctorDto> map(List<Doctor> doctors);
DoctorDto map(Doctor doctor);
}

最新更新