Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MapStruct avoid return object creation

Tags:

java

mapstruct

I have two models and a mapper,

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);
}

This is my example,

// 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 is generating source code which inside creates a new Domain object.
Running the last command domain = DomainMapper.toDomain(form); my previous domain object will be lost. Is there any way to transfer properties from a Form object to a Domain object that I have already created, using MapStruct?
I tried something like this, but it is not working,

@Mapper
public interface DomainMapper {

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

I used it like this, but it doesn't work,

domainMapper.toDomain(form, domain);
like image 518
Georgios Syngouroglou Avatar asked Mar 09 '23 21:03

Georgios Syngouroglou


1 Answers

I will set as answer the @seneque's comment.
I can pass a reference of an object, so the mapper will not create a new one, by using the annotation @MappingTarget.

void updateDomain(Form form, @MappingTarget Domain domain)
like image 162
Georgios Syngouroglou Avatar answered Mar 19 '23 12:03

Georgios Syngouroglou