首页 > 解决方案 > ModelMapper 错误地映射到嵌套对象属性

问题描述

我正在使用 ModelMapper 将 DTO 映射到实体,反之亦然。当我将 a 映射ChildDTO到类和类Child都具有相同名称的属性时,我遇到了问题。ChildParent

这些是对象:

public class Child {

    @Id
    @EqualsAndHashCode.Include
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;

    private String name; // <---- property called 'name'
    // other properties

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_id")
    private Parent parent;
}

public class Parent {

    @Id
    @EqualsAndHashCode.Include
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;

    private String name; // <---- property called 'name'
    // other properties

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Child> items = new ArrayList<>();
}

public class ChildDTO {

    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private Long id;

    private String name;
    // other properties

    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private Long parentId;
}

这是进行映射的代码:

ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
modelMapper.getConfiguration().setAmbiguityIgnored(true);
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);

Child childItem = repository.findById(id);

ChildDTO childItemDTO = new ChildDTO();
childItemDTO.setName("new name");

modelMapper.map(childItemDTO, childItem);

这导致两者都 Child::name 更改 Parent::name为“新名称”。请注意,我已经在使用STRICT映射策略。

从到Parent::setName()映射时,我也找不到跳过呼叫的方法ChildDTOChild

模型映射器版本:2.3.2

标签: javamodelmapper

解决方案


推荐阅读