0
votes

Mapstruct used my own parameters-free method as factory for List (instead of constructor)

I tried to map some objects tree, that should built level by level. So i have a method for hardcoded root nodes and another methods, that used for mapping entities to nodes. So i have a method for generation list of root names, and abstract methods for mapping.

@Mapper
public abstract class TestMapper {

public List<Name> rootNames() {
    List<Name> names = new ArrayList<>();
    names.add(Name.build("Homer"));
    names.add(Name.build("Marge"));
    return names;
}

@Mapping(target = "name", source = "name")
public abstract Name childrenName(FullName simpson);

public abstract List<Name> childredNames(List<FullName> children);

public static class Name {
    private String name;

    public static Name build(String value) {
        Name name = new Name();
        name.setName(value);
        return name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public static class FullName {
    private String name;
    private String lastName;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

}

So in generated code "childrenNames" looks like @Override public List childrenNames(List children) { if ( children == null ) { return null; }

    List<Name> list = rootNames();
    for ( FullName fullName : children ) {
        list.add( simpsonName( fullName ) );
    }

    return list;
}

How i can mark my rootNames method as ignored for mapping?

Best regards. Alexey

1

1 Answers

1
votes

As discussed in the ticket https://github.com/mapstruct/mapstruct/issues/1725 you should add the @Named annotation to your rootNames() method. Without the annotation it will be picked up automatically as an object factory by MapStruct (see http://mapstruct.org/documentation/dev/reference/html/#object-factories).

As soon as a method is annotated with @Named it will only be picked up when referenced explicitely.

@org.mapstruct.Named("rootNames")
public List<Name> rootNames() {
    List<Name> names = new ArrayList<>();
    names.add(Name.build("Homer"));
    names.add(Name.build("Marge"));
    return names;
}