简体   繁体   中英

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

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;
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM