Ghen
Ghen

Reputation: 63

Mapstruct: Mapping multiple source objects to subobjects

Given a set of four objects like:

A{String one, B b}

B{String two, String three}

C{String one, String two}

D{String three}

I wish to generate a mapping like:

A cAndDToA(C c , D d);

I cannot currently find a way to populate the B object inside of A with data from both C and D.

Does anyone know a solution to this issue, or have a better approach?

Upvotes: 6

Views: 7423

Answers (1)

Gunnar
Gunnar

Reputation: 18970

You could define a method for populating the B from C and D:

B cAndDToB(C c, D d);

And then invoke this manually via a decorator on cAndDToA:

@Mapper(decoratedWith=MyMapperDecorator.class)
public interface MyMapper {
    A cAndDToA(C c, D d);
    B cAndDToB(C c, D d);
}

public abstract class MyMapperDecorator implements MyMapper {

    private final MyMapper delegate;

    public MyMapperDecorator(MyMapper delegate) {
        this.delegate = delegate;
    }

    @Override
    public A cAndDToA(C c, D d) {
        A a = delegate.cAndDToA( c, d );
        a.setB( cAndDToB( c, d );

        return a;
    }
}

We will offer support for nested mappings on the target side, too. But we are not there yet :)

Upvotes: 7

Related Questions