How to apply the function of two argument mapping objects using MapStruct?

There are two classes of sources A and B

class A {
    public Double x;
    public Double y;
}

class B {
    public Double x;
    public Double y;
}

and another target class C

class C {
    public Double x;
    public Double y;
}

It is clear how to match AC or B from C.

Is it possible to map some function, for example, adding or a pool of source objects to the target, so that the generated code looks like this:

C.x = A.x + B.x
C.y = A.y + B.y

or

C.x = Math.pow(A.x, B.x)
C.y = Math.pow(A.y, B.y)
+4
source share
1 answer

This can be done using expressions.

@Mapper
public interface MyMapper {

    @Mapping(target = "x", expression = "java(a.x + b.x)")
    @Mapping(target = "y", expression = "java(a.y + b.y)")
    C map(A a, B b);
}

or

@Mapper
public interface MyMapper {

    @Mapping(target = "x", expression = "java(Math.pow(a.x, b.x))")
    @Mapping(target = "y", expression = "java(Math.pow(a.y, b.y))")
    C map(A a, B b);
}

More information on expressions can be found in the help documentation here.

+1
source

Source: https://habr.com/ru/post/1680351/


All Articles