Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply function of two arguments mapping objects using MapStruct?

Tags:

java

mapstruct

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)
like image 864
user8227598 Avatar asked Jun 28 '17 17:06

user8227598


People also ask

How do I map a MapStruct collection?

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.

How does MapStruct generate implementation?

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.

What is componentModel in MapStruct?

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()


1 Answers

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

like image 142
Filip Avatar answered Oct 06 '22 01:10

Filip