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

ModelMapper空对象属性映射异常:如何配置将目标属性设为null?

How to Make ModelMapper Set Target Property to Null When Source Property Is Null

Absolutely! You can configure ModelMapper to get the exact behavior you want. The issue you’re seeing—where userDto.status becomes an empty StatusDto with all null fields instead of straight-up null—is ModelMapper’s default behavior: when a source property is null, it tries to instantiate the target type rather than just setting the property to null. Here are two simple ways to fix this:

Method 1: Adjust Null Value Handling Configuration

The easiest approach is to tweak ModelMapper’s core configuration to set target properties to null whenever the corresponding source property is null. This works great for cases where your source and target types have matching structures (like your Status and StatusDto).

Update your ModelMapper setup code like this:

ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration()
    .setNullValuePropertyMappingStrategy(NullValuePropertyMappingStrategy.SET_TO_NULL);

What this does:

By setting NullValuePropertyMappingStrategy.SET_TO_NULL, you’re telling ModelMapper: "If the source property is null, don’t create a new instance of the target type—just set the target property to null directly." This overrides the default behavior that was creating that empty StatusDto object.

Method 2: Use a Custom Converter (For Fine-Grained Control)

If you need more control over how Status maps to StatusDto (for example, if you have custom field mappings or business logic to apply), you can create a converter that explicitly returns null when the source is null:

ModelMapper modelMapper = new ModelMapper();

// Create a converter to handle Status -> StatusDto mapping
Converter<Status, StatusDto> statusConverter = context -> {
    Status sourceStatus = context.getSource();
    if (sourceStatus == null) {
        return null; // Return null immediately when source is null
    }
    // Normal mapping logic for non-null source objects
    StatusDto targetDto = new StatusDto();
    targetDto.setId(sourceStatus.getId());
    targetDto.setName(sourceStatus.getName());
    return targetDto;
};

// Register the converter with ModelMapper
modelMapper.addConverter(statusConverter);

Verify the Fix

After applying either of these solutions, running your code will produce the output you expect:

user = ModelMapperTest.User(status=null)
userDto = ModelMapperTest.UserDto(status=null)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 22:03:10