How to have MapStruct not generate wrapper object if property is null?

Jorn :

I have some code that uses MapStruct to map a from.id to a to.ref.id structure. When from.id is null, MapStruct will create a new Reference instance and set its id to null. How do I instead make it not generate the wrapper class, and set to.ref to null?

I've tried different values for the mapping's nullValueCheckStrategy and nullValuePropertyMappingStrategy, but those don't seem to make any difference for this case.

This is my code, getters and setters omitted for brevity.

public class Example {
    public static void main(String[] args) {
        System.out.println(Mappers.getMapper(MyMapper.class).get(new From()));
    }
}

@Mapper
interface MyMapper {
    @Mapping(source = "id", target = "ref.id")
    To get(From from);
}

class From {
    private String id;
}

class To {
    private Reference ref;
}

class Reference {
    private String id;
}
greenPadawan :

You can try something like this

Create a new mapper as follows.

@Mapper
public interface Mapper1 {
    @Mapping(source = "id", target = "id")
    Reference get(String id);
}

Then update you exiting mapper to use this new mapper like this

@Mapper(uses = Mapper1.class)
public interface MyMapper {

    @Mapping(source = "from.id", target = "ref")
    To get(From from);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=147433&siteId=1