There are two source classes 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 map A to C or B to C.
Is it possible to map some function, for example, addition or pow of source objects to the target one so that the generated code will look 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)
In general, mapping collections with MapStruct works the same way as for simple types. Basically, we have to create a simple interface or abstract class, and declare the mapping methods. Based on our declarations, MapStruct will generate the mapping code automatically.
MapStruct is an open-source Java-based code generator which creates code for mapping implementations. It uses annotation-processing to generate mapper class implementations during compilation and greatly reduces the amount of boilerplate code which would regularly be written by hand.
Enclosing class: MappingConstants public static final class MappingConstants.ComponentModel extends Object. Specifies the component model constants to which the generated mapper should adhere. It can be used with the annotation Mapper.componentModel() or MapperConfig.componentModel()
This can be done by 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 info about expressions can be found in the reference documentation here
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