You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用ModelMapper仅将源对象字段值映射到目标对象空/Null字段?

问题描述

现有Foo和Bar两个结构相似的类,使用ModelMapper进行字段映射时,默认会覆盖目标对象的所有字段值,但我们需要实现仅填充目标对象的空/Null字段、保留非空值的逻辑。

相关代码

Foo类

class Foo {
    public Foo(int fooId, String name, int age) {
        this.fooId = fooId;
        this.name = name;
        this.age = age;
    }

    private int fooId;
    private String name;
    private int age;

    // Getters, Setters, toString方法已省略
}

Bar类

class Bar {
    public Bar(int fooId, String name, int age) {
        this.fooId = fooId;
        this.name = name;
        this.age = age;
    }

    private int fooId;
    private String name;
    private int age;

    // Getters, Setters, toString方法已省略
}

测试代码

public class Mapper {
    public static void main(String args[]) throws IOException {
        Foo foo = new Foo(1, "ABC", 30);            
        Bar bar = new Bar(2, null, 25);
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.map(foo, bar);      
        System.out.println(bar.toString());
    }
}

结果对比

  • 实际输出:Bar [fooId=1, name=ABC, age=30]
  • 预期输出:Bar [fooId=2, name=ABC, age=25]
解决方案

利用ModelMapper的**条件映射(Condition)**功能,自定义判断规则:仅当目标字段为null时才执行赋值操作。

全局配置方案(所有字段生效)

public class Mapper {
    public static void main(String args[]) throws IOException {
        Foo foo = new Foo(1, "ABC", 30);            
        Bar bar = new Bar(2, null, 25);
        
        ModelMapper modelMapper = new ModelMapper();
        // 设置全局映射条件:目标字段为null时才覆盖
        modelMapper.getConfiguration()
                   .setPropertyCondition(context -> context.getDestination() == null);
        
        modelMapper.map(foo, bar);      
        System.out.println(bar.toString());
    }
}

精细化配置方案(指定字段生效)

如果只需要对特定字段应用该规则,可通过TypeMap单独配置:

public class Mapper {
    public static void main(String args[]) throws IOException {
        Foo foo = new Foo(1, "ABC", 30);            
        Bar bar = new Bar(2, null, 25);
        
        ModelMapper modelMapper = new ModelMapper();
        // 创建Foo到Bar的类型映射
        TypeMap<Foo, Bar> typeMap = modelMapper.createTypeMap(Foo.class, Bar.class);
        
        // 仅对name字段应用"目标为null才覆盖"的规则
        typeMap.addMappings(mapper -> 
            mapper.when(context -> context.getDestination() == null)
                  .map(Foo::getName, Bar::setName));
        
        modelMapper.map(foo, bar);      
        System.out.println(bar.toString());
    }
}

运行上述代码后,输出结果将符合预期:Bar [fooId=2, name=ABC, age=25]

内容的提问来源于stack exchange,提问作者Hullar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 08:40:19