-2

So I have a source Object Obj1 and a target Object Obj2. I created a mapper interface Object1Mapper which maps from Obj1 to Obj2. However, no errors show up and I don't understand why.

@Data
@Entity
@Table(name="test")
@NoArgsConstructor
public class Obj1 {
    private String val1;
    private String val2;

    public Obj1(String val1, String val2){
        this.val1 = val1;
        this.val2 = val2;
}
@Data
public class Obj2 {
    private String val1;
}
@Mapper
public interface Object1Mapper {

    Object1Mapper INSTANCE = Mappers.getMapper(Object1Mapper.class);

    Obj2 obj1ToObj2(Obj1 obj1);
}

When I do

obj1 = new Obj1("aa", "bb")
System.out.println(Object1Mapper.INSTANCE.obj1ToObj2(o_1obj1));

it prints out 'Obj1(value1=aa)'

In the mapper Implementation there are only setters for the attributes of the target object Obj2 created. So are only those attributes automatically mapped which exist in the source and target Object?

Luca Basso Ricci
  • 17,829
  • 2
  • 47
  • 69
insomnius
  • 3
  • 2
  • Mapping behaviours and conventions are described in official documentation in a very clear manner; check it to get all the answers. (https://mapstruct.org/documentation/stable/reference/html/#basic-mappings) – Luca Basso Ricci Sep 16 '22 at 13:47

1 Answers1

0

So are only those attributes automatically mapped which exist in the source and target Object?

That is right. There is only need of mapping target attributes. And you have to configure all mapping targets. E.g. if you want to map Obj2 to Obj1 you have to configure not mapping val2

@Mapping(target="val2" ignore="true")
Obj1 obj2ToObj1(Obj2 obj2)
Michael Katt
  • 615
  • 1
  • 5
  • 18