MapStruct避免返回对象创建

时间:2017-02-14 13:02:05

标签: java mapstruct

我有两个模型和一个映射器,

public class Form {
    private int x1;
    private int x2;
    private int x3;
    private int x4;
    // Constructor and getters setters ommited.
}

public class Domain {
    private int x1;
    private int x2;
    private int x3;
    private int x4;
    // Constructor and getters setters ommited.
}

@Mapper
public interface DomainMapper {

    @Mappings({
        @Mapping(target = "x1", ignore = true),
        @Mapping(target = "x2", ignore = true)})
    Domain toDomain(Form form);
}

这是我的例子,

// I create a form object.
Form form = new Form();
form.setX1(1);
form.setX2(2);
form.setX3(3);
form.setX4(4);

// I create a Domain object.
Domain domain = new Domain();
domain.setX1(100);
domain.setX2(200);

// Map the form to domain.
domain = domainMapper.toDomain(form);
System.out.print(domain.getX1()); // => shows "0" instead of "100"

MapStruct正在生成源代码,内部创建一个新的Domain对象 运行最后一个命令domain = DomainMapper.toDomain(form);我之前的域对象将丢失。有没有办法使用MapStruct将属性从Form对象传输到我已经创建的Domain对象? 我试过这样的东西,但它不起作用,

@Mapper
public interface DomainMapper {

    @Mappings({
        @Mapping(target = "x1", ignore = true),
        @Mapping(target = "x2", ignore = true)})
    Domain toDomain(Form form, Domain referenceToExistingObject);
}

我这样使用它,但它不起作用,

domainMapper.toDomain(form, domain);

1 个答案:

答案 0 :(得分:1)

我将回答@seneque的评论 我可以传递对象的引用,因此映射器不会使用注释@MappingTarget创建新对象。

void updateDomain(Form form, @MappingTarget Domain domain)