java - ModelMapper 错误地映射到嵌套对象属性
问题描述
我正在使用 ModelMapper 将 DTO 映射到实体,反之亦然。当我将 a 映射ChildDTO
到类和类Child
都具有相同名称的属性时,我遇到了问题。Child
Parent
这些是对象:
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()
映射时,我也找不到跳过呼叫的方法ChildDTO
Child
模型映射器版本:2.3.2
解决方案
推荐阅读
- php - PostgreSQL 中的 ID 列 (Laravel 5.8)
- excel - 具有四个输出选项的 Excel IF 和 AND 形式
- laravel - 如何在 laravel 的编辑表单中检索单选按钮、复选框和多选的值
- python - 字符串列 Pandas 数据框的中位数
- nginx - 403 Forbidden: "/path/to/files" 的目录索引被禁止 Nginx
- php - 电子邮件管道脚本在后缀中以无人身份而不是真实用户身份运行
- php - 教义 findBy() 在同一行重复 n 次
- javascript - 需要帮助重构我的 Javascript 代码 (D3)
- python-3.x - 有没有办法获取整个 IMDB 评论数据库?
- ms-office - 如何有条件地删除excel中的值?