Search code examples
javamapstruct

How to exclude a field when its id is empty in mapStruct?


i am new at mapStruct and i don't know how to exclude a field when it's empty.

The Classes look like these:

public class MyClass {
    String reference;
    Info info;
    ...
}

public class Info{
    Long id;
    List<String> parts = new ArrayList<>();
    ...
}

And this is the mapper:

@Mapping(target = "info.id", source = "infoId")
public abstract MyClass toMyClass(RequestProto.line Line);

So when the info.id comes empty i get MyClass instantiated with the parameter info with an empty list of parts.

MYCLASS(current)
{
    reference: "aa",
     info: {
       parts: []
     }  
}

What i want is that when the info.id is empty the info parameter is null.

MYCLASS(expected)
{
    reference: "aa" 
    info: null
}

I have no idea how to achieve this.

I hope i explained my self. If someone can bring me some light with this would be much appreciated


Solution

  • You could use your own logic for it:

    @Mapping(target = "info", source = "Line", qualifiedByName = "info")
    public abstract MyClass toMyClass(RequestProto.line Line);
    
    @Named("info")
    public Info mapInfo(RequestProto.line Line) {
       if(infoId.isEmpty()) {
          return null;
       }
       Info info = new Info();
       info.setId(infoId);
       return info;
    }
    

    or you could create new class for it:

    @Mapper(uses = {InfoMapper.class}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
    public MyClassMapper {
    
       @Mapping(target = "info", source = "Line", qualifiedByName = "info")
       public abstract MyClass toMyClass(RequestProto.line Line);
    }
    public class InfoMapper implements Function<Info, RequestProto.line> {
    
       @Override
       @Named("info")
       public Info apply(RequestProto.line Line) {
       //pseudo code, make it better based on your request object
          if(infoId.isEmpty()) {
              return null;
          }
          Info info = new Info();
          info.setId(infoId);
          return info;
       }