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
相关产品推荐
相关产品推荐

