ModelMapper 对不同属性感到困惑

10

我有一个扩展自Person对象的Student对象。

public abstract class Person implements IIdentifiable {
    private String contactNumber;
    // other properties
    public String getContactNumber() {
        return contactNumber;
    }

    public void setContactNumber(String contactNumber) {
        this.contactNumber = contactNumber;
    }
}

public class Student extends Person {
    private String studentNumber;
    //Other properties
    public String getStudentNumber() {
        return studentNumber;
    }

    public void setStudentNumber(String studentNumber) {
        this.studentNumber = studentNumber;
    }
}

学生拥有一个名为studentNumber的属性,而人具有一个名为contactNumber的属性。当我将学生对象映射到StudentDto时,它会对给定属性感到困惑。

public class StudentDto{
    private String studentNumber;
    public String getStudentNumber() {
        return studentNumber;
    }

    public void setStudentNumber(String studentNumber) {
        this.studentNumber = studentNumber;
    }
}

这只会在某些特定场合发生。我想知道原因是什么。

1) The destination property com.cinglevue.veip.web.dto.timetable.StudentDto.setStudentNumber() matches multiple source property hierarchies:
com.cinglevue.veip.domain.core.student.StudentProfile.getStudent()/com.cinglevue.veip.domain.core.Person.getContactNumber()
com.cinglevue.veip.domain.core.student.StudentProfile.getStudent()/com.cinglevue.veip.domain.core.Student.getStudentNumber()

请您能否发布您尝试过的代码,以及Student和Person类。 - Vishal Gajera
当然。我会更新帖子。 - Susitha Ravinda Senarath
你能发布一下你的ModelMapper配置和映射代码吗?或者在出错时将代码贴出来。 - Pau
2个回答

5

1. 你可以使用以下方式更改MatchingStrategies

modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);

PS:ModelMapper隐式地使用MatchingStrategies.STANDARD

但它要求源和目标端的属性名称标记精确匹配。

2. 告诉ModelMapper在找到多个源属性层次结构时忽略映射:

modelMapper.getConfiguration().setAmbiguityIgnored(true);

我现在记不起来为什么会出现这个问题了。无论如何,可能有人会受益。谢谢。 - Susitha Ravinda Senarath

4

自从你提问以来已经过了很长时间。由于这里没有答案,我向您展示了对我有效的解决方案。

该问题是由目标属性名称导致ModelMapper混淆而引起的。

因此,为了解决这个问题,我们需要执行两个步骤:

1. 告诉ModelMapper忽略可能会引起混淆的内容。

2. 为混淆的属性指定映射。

详细代码如下:

ModelMapper modelMapper = new ModelMapper();

modelMapper.getConfiguration().setAmbiguityIgnored(true);

modelMapper.createTypeMap(Student.class, StudentDto.class)
    .addMapping(Student::getStudentNumber, StudentDto::setStudentNumber);

是的,我现在记不起来为什么会出现这个问题了。无论如何,可能有人会受益。谢谢。 - Susitha Ravinda Senarath
如何使用嵌套对象实现这个? - TheLebDev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接