【问题标题】:ModelMapper get confuse on different propertiesModelMapper 对不同的属性感到困惑
【发布时间】:2016-03-25 07:19:19
【问题描述】:

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

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;
    }
}

Student 拥有 studentNumber 的属性,而 person 拥有 contactNumber 的属性。当我将 Student 对象映射到 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()

【问题讨论】:

  • 能否请您发布您尝试过的代码,以及学生和个人课程
  • 当然。我更新帖子
  • 您能发布您的 ModelMapper 配置和地图吗?或者只是发生错误时的代码案例图。

标签: java modelmapper


【解决方案1】:

1. 您可以更改MatchingStrategies,使用:

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

PS:modelmapper 隐式使用MatchingStrategies.STANDARD

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

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

modelMapper.getConfiguration().setAmbiguityIgnored(true);

【讨论】:

  • 我不记得为什么我现在遇到这个问题了。无论如何,有人可能会受益。谢谢
【解决方案2】:

很久没问了。由于这里没有答案,我向您展示我的解决方案对我来说很有效。

该问题是由目标属性名称引起的,让 ModelMapper 感到困惑。 所以,要解决这个问题,我们需要做两个步骤。 1. 假设 ModelMapper 忽略了一些可能令人困惑的东西。 2. 指定混淆属性的指示映射。

详细代码在这里:

ModelMapper modelMapper = new ModelMapper();

modelMapper.getConfiguration().setAmbiguityIgnored(true);

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

【讨论】:

  • 是的,我不记得为什么我现在遇到这个问题了。无论如何,有人可能会受益。谢谢
猜你喜欢
  • 1970-01-01
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-27
  • 1970-01-01
相关资源
最近更新 更多