java - 如何使用 mapstruct 或 modelmapper 从一个对象递归更新嵌套对象?
问题描述
最好我通过一个我想要得到的例子来解释我的任务。是否可以使用 mapstruct / modelmapper / 等来解决这个问题?
class Person{
String name;
Address address;
}
class Address{
String street;
Integer home;
}
更新:
{
name: "Bob"
address: {
street: "Abbey Road"
}
}
目标:
{
name: "Michael"
address: {
street: "Kitano"
home: 5
}
}
结果我想得到:
{
name: "Bob"
address: {
street: "Abbey Road"
home: 5
}
}
它不能重写地址对象。它递归地在其中设置新值。
解决方案
是的,您可以使用从 MapStruct更新现有 bean 实例来执行您正在寻找的更新。
映射器看起来像:
@Mapper(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE, nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS)
public interface PersonMapper {
void update(@MappingTarget Person toUpdate, Person person);
void update(@MappingTarget Address toUpdate, Address address);
}
为此生成的代码如下所示:
public class PersonMapperImpl implements PersonMapper {
@Override
public void update(Person toUpdate, Person person) {
if ( person == null ) {
return;
}
if ( person.getName() != null ) {
toUpdate.setName( person.getName() );
}
if ( person.getAddress() != null ) {
if ( toUpdate.getAddress() == null ) {
toUpdate.setAddress( new Address() );
}
update( toUpdate.getAddress(), person.getAddress() );
}
}
@Override
public void update(Address toUpdate, Address address) {
if ( address == null ) {
return;
}
if ( address.getStreet() != null ) {
toUpdate.setStreet( address.getStreet() );
}
if ( address.getHome() != null ) {
toUpdate.setHome( address.getHome() );
}
}
}
nullValuePropertyMappingStrategy
- 当源 bean 属性存在null
或不存在时应用的策略。默认是将值设置为目标值null
nullValueCheckStrategy
- 确定何时包括null
对 bean 映射的源属性值的检查
注意来自nullValuePropertyMappingStrategy
MapStruct 1.3.0.Beta2
推荐阅读
- android - 如何降低位图的分辨率
- wpf - 如何使用样式的触发器但覆盖行为
- nfc - ACR1252 Felica 仿真
- javascript - 监听 mongoDB 中的更新操作并自动更新某些字段
- javascript - 查找数组数组中的第一个元素,第二个元素具有最高值
- r - 是否可以在 R 中使用来自 data.table 的 fwrite 来编写一个带有 sep="" 的表
- java - 用于扑克的 Java 蒙特卡罗模拟
- android - Flutter:未知的操作系统。无法安装 Dart SDK
- javascript - 完整日历不会显示取自 AJAX 的事件
- python - 如何将 pandas DataFrame 插入 Microsoft SQL Server 表?