我有父类和子类,分别有如下DTO
class Parent {
List<Child> children;
// setters and getters
}
class Child {
Parent parent;
}
class ParentDto {
List<ChildDto> children;
// setters and getters
}
class ChildDto {
ParentDto parent;
// setters and getters
} 当我尝试将Parent映射到ParentDto时,我得到了StackOverflowError。
请帮我解决这个问题。
发布于 2018-06-20 20:21:14
我知道这篇文章很旧,但我会试着给出一个答案,以防来自谷歌的人到达这里。
你可能有一个动态的对象创建。
最近我遇到了这样的问题。在我的例子中,我有一个类Student,它扩展了Person。Person还有另外三个Person类型的属性:父亲、母亲和负责。以防万一,我有一个循环关系。当我运行我的JUnits测试时,我得到了一个循环调用。我没有得到一个stakOverflow,因为Spring (在一段时间之后)关闭了数据库连接。
我解决了这个问题,从Person类中删除了创建的动力学对象。
解决这个问题的另一种方法是在映射器中添加一个条件。您可以阅读有关conditions here的更多信息。例如,您可以设置一些条件:“如果person属性id为10,则不需要映射它。”这样我们就可以避免无限映射。好吧,让我们来看一些代码片段:
学生班级:
public class Student extends Person implements IStudent {
private Person financialResponsible;
// Getters and setters.
}Person类:
public class Person implements IPerson {
private Long id;
private String name;
private Person father;
private Person mother;
private Person responsible;
private Address address;
// Getters and setters.
// This is my real problem. I removed it and the mapper worked.
public IPerson getFather() {
if (father == null) father = new Person();
return father;
}
} StudentDTO类:
public class StudentDTO extends PersonDTO {
private PersonDTO financialResponsible;
// Getters and setters.
}PersonDTO类:
public class PersonDTO {
private Long id;
private String name;
private PersonDTO father;
private PersonDTO mother;
private PersonDTO responsible;
private AddressDTO address;
// Getters and setters.
}下面是一个条件示例:
...
import org.modelmapper.Condition;
...
ModelMapper mapper = new ModelMapper();
// Define STRICT to give high precision on mapper.
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
/*
* Create conditions to avoid infinity circularity.
*/
// Condidions.
final Condition<IStudent, StudentDTO> fatherIsTen = mappingContext -> mappingContext.getSource().getFather().getId() == 10;
final Condition<IStudent, StudentDTO> motherIsTen = mappingContext -> mappingContext.getSource().getMother().getId() == 10;
final Condition<IStudent, StudentDTO> resposibleIsTen = mappingContext -> mappingContext.getSource().getResponsible().getId() == 10;
// Adding conditions on mapper.
mapper.createTypeMap(IStudent.class, StudentDTO.class) //
.addMappings(mapper -> mapper.when(fatherIsTen).skip(StudentDTO::setFather))
.addMappings(mapper -> mapper.when(motherIsTen).skip(StudentDTO::setMother))
.addMappings(mapper -> mapper.when(resposibleIsTen).skip(StudentDTO::setResponsible));我希望能帮上忙
https://stackoverflow.com/questions/41163924
复制相似问题