mapstruct:使用来自 DTO 的数据更新实体的现有字段

yar*_*Tir 7 mapstruct

我最近在我的项目中添加了 mapStruct。这个框架很酷,但我想不出一件事。

这是我的情况:我有类型的Profile实体和字段Person。我想使用ProfileDto. 我正在void fromDto(ProfileDto dto, @MappingTarget Profile entity)为此使用方法。问题是映射器总是创建新的人而不是使用profile实体中的人

我的实体是:

public class Profile  {
    private Person person;
    .. setters, getters and  constructors 
}

public class Person extends AbstractEntity {
    private String name;
    private String surname;
    .. setters, getters and  constructors 
}
Run Code Online (Sandbox Code Playgroud)

public class ProfileDto  extends AbstractDto {
    private String name;
    private String surname;
    .. setters, getters and  constructors 
}
Run Code Online (Sandbox Code Playgroud)

我的映射器

public abstract class ProfileMapper {

    @Mappings({
            @Mapping(target = "name", source = "entity.person.name"),
            @Mapping(target = "surname", source = "entity.person.surname")

    })
    public abstract ProfileDto toDto(Profile entity);

    @InheritInverseConfiguration(name = "toDto")
    public abstract void fromDto(ProfileDto dto, @MappingTarget Profile entity);
}
Run Code Online (Sandbox Code Playgroud)

生成的代码

      @Override
        public void fromDto(ProfileDto dto, Profile entity) {
            if ( dto == null ) {
                return;
            }
            Person person = new Person();
            entity.setPerson( person );
...
Run Code Online (Sandbox Code Playgroud)

我不需要在这里创建新的 person 实例

人 = 新人();

我以某种方式将此字符串替换为:

人 = entity.getPerson()

Fil*_*lip 5

这是一个已知问题,请参阅#1011。这已得到改进1.2.0(在撰写本文时,最新版本是 2017 年 7 月 11 日1.2.0.Beta3)。您应该尝试最新版本,它应该按预期工作。