MappingConstants.NULL example

In this post under MapStruct, I will explain with example the purpose of MappingConstants.NULL enum constant.

In all my previous posts, I explained how to map a source enum constant to destination enum constant.

What if the client calling the code (that will map passed source enum constant to destination enum constant) passes a null value.

We need to program our mapping code to handle those scenarios also.

That is where the enum constant MappingConstants.NULL comes into picture.

This enum constant is used to represent a null value.

In the mapping code, we can use the above enum constant to tell MapStruct that if client passes null, this is how you have to respond.

Below is the example of mapping interface

If we have below source enum

Source enum

package package15;

public enum Day {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY;
}

and below destination enum

Destination enum

package package15;

public enum Week {
    WEEK_DAY,
    WEEK_END;
}

The mapping interface will be as shown below

Mapping interface

  package package15;

  import org.mapstruct.Mapper;
  import org.mapstruct.MappingConstants;
  import org.mapstruct.ValueMapping;
  import org.mapstruct.ValueMappings;

  @Mapper
  public interface DayToWeekMapper {
     @ValueMappings({
             @ValueMapping(source = "MONDAY", target = "WEEK_DAY"),
             @ValueMapping(source = "TUESDAY", target = "WEEK_DAY"),
             @ValueMapping(source = "WEDNESDAY", target = "WEEK_DAY"),
             @ValueMapping(source = "THURSDAY", target = "WEEK_DAY"),
             @ValueMapping(source = "FRIDAY", target = "WEEK_DAY"),
             @ValueMapping(source = MappingConstants.ANY_UNMAPPED, target = "WEEK_END"),
             @ValueMapping(source = MappingConstants.NULL, target = MappingConstants.THROW_EXCEPTION)
     })
     Week dayToWeekMapping(Day day);
}

In the above mapping code, at line 17, I am instructing MapStruct that if you encounter null value in place of source enum constant throw an exception.

Below is the main class for your reference

Main class

package package15;

import org.mapstruct.factory.Mappers;

public class Example15 {
    public static void main(String[] args) {
        DayToWeekMapper dayToWeekMapper = Mappers.getMapper(DayToWeekMapper.class);

        Week week = dayToWeekMapper.dayToWeekMapping(Day.THURSDAY);
        System.out.println(week);
        week = dayToWeekMapper.dayToWeekMapping(Day.SUNDAY);
        System.out.println(week);
        week = dayToWeekMapper.dayToWeekMapping(null);
        System.out.println(week);
    }
}

The output will be

Output

WEEK_DAY
WEEK_END
Exception in thread "main" java.lang.IllegalArgumentException: Unexpected enum constant: null
    at MapStructConcepts.main/package15.DayToWeekMapperImpl.dayToWeekMapping(DayToWeekMapperImpl.java:15)
    at MapStructConcepts.main/package15.Example15.main(Example15.java:13)

Leave a comment