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

MapStruct无法更新已有目标对象问题求助

解决MapStruct更新已有Bean实例失败的问题

核心原因

更新操作失败的本质是目标对象Destination未提供可修改属性的setter方法。即便你移除了字段的final修饰符,若没有添加public的setter方法,MapStruct无法生成属性赋值逻辑,自然无法更新目标实例的属性。此外,接口命名Mapper易与MapStruct的@Mapper注解混淆,建议修改以避免潜在问题。

修正步骤

1. 修正Destination类,添加setter方法

移除字段的final修饰符,并为每个属性添加public的setter:

public class Destination {
    private String id;
    private String other;

    public Destination(String id, String other) {
        this.id = id;
        this.other = other;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getOther() {
        return other;
    }

    public void setOther(String other) {
        this.other = other;
    }
}

2. 修改Mapper接口名称(可选但推荐)

避免与org.mapstruct.Mapper注解重名,降低代码混淆风险:

import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.mapstruct.factory.Mappers;

@Mapper
public interface SourceDestinationMapper {
 
    SourceDestinationMapper INSTANCE = Mappers.getMapper(SourceDestinationMapper.class);
 
    Destination createDestinationFromSource(Source source);
    void updateDestinationFromSource(Source source, @MappingTarget Destination destination);
}

3. 重新编译项目

如果之前修改代码后未生效,执行clean命令后重新编译,确保MapStruct处理器生成最新的映射实现类。

修正后的测试代码

@Test
void testMapStruct() {
    // Create
    var source = new Source("sourceId", "sourceOther");
    var destination1 = SourceDestinationMapper.INSTANCE.createDestinationFromSource(source);
    Assertions.assertEquals(source.getId(), destination1.getId());

    // Update
    var destination2 = new Destination("destinationId", "destinationOther");
    SourceDestinationMapper.INSTANCE.updateDestinationFromSource(source, destination2);
    Assertions.assertEquals(source.getId(), destination2.getId()); // 现在会通过
}

额外说明

  • MapStruct更新Bean实例的逻辑依赖目标对象的setter方法,若字段为final且无setter,MapStruct会跳过该字段的更新
  • 确保mapstruct-processor依赖在编译阶段生效,它负责生成映射实现类,缺失或版本不匹配会导致功能异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:55:30