1
votes

I have implementation of mapstruct Mapper as following

@Mapper
public interface MyMapper extends Serializable {
    MyMapper INSTANCE = Mappers.getMapper(MyMapper.class);

    //@Mapping(target = "status", source = "p1.status")
    MergedPojosClass from(Pojo1 p1, Pojo2 p2);
}

In the target class I have field status but this field is available in both pojo classes. For my pojos I use lombok to generate setters, getters and all kind of constructors.

Without commented line I receive following error:

Error:(20, 14) java: Several possible source properties for target property "status".

Can I avoid above boilerplate (explicit mapping) by adding some annotation saying that Pojo1 has higher priority? I was looking into Java docs and also to source code of mapstruct but without any example or clue which could help in my case. I was trying to find something with InheritanceStrategy but it looks rather like internal concept of mapstruct.

2

2 Answers

0
votes

You could try to define an @MapperConfig. Not sure if it works though

So like this:

@MapperConfig
public interface MyConfig {
    @Mapping(target = "status", source = "p1.status")
    MergedPojosClass from(Pojo1 p1);
}

@Mapper(config = MyConfig.class, mappingInheritanceStrategy=MappingInheritanceStrategy.AUTO_INHERIT_ALL_FROM_CONFIG)
public interface MyMapper extends Serializable {
    MyMapper INSTANCE = Mappers.getMapper(MyMapper.class);

    // here's the doubt.. I'm not sure that in 2 arg mapping the config is used
    MergedPojosClass from(Pojo1 p1, Pojo2 p2);
}
0
votes

If you want to merge several objects of the same type into one you can use @MappingTarget. However this approach modifies the parameter. If you want to produce a new object you'd need something like this:

@Mapper(nullValuePropertyMappingStrategy = IGNORE)
public interface PojoMerger {
    void copyNonNullProperties(@MappingTarget Pojo target, Pojo source);

    default Pojo merge(Pojo... sources) {
        Pojo merged = new Pojo();

        for(Pojo source: sources) {
            copyNonNullProperties(merged, source);
        }

        return merged;
    }
}