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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With