0

I want to return null from my mapper method if a complex condition is met, but mapstruct ignores null value returned from @AfterMapping method, so How can I achieve this?

The code below has comments that demonstrate what I need

class User{
    String name;
    Role role;
    Date birthDate;
}



@Mapper(componentModel = "spring")
interface UserMapper{
    Inner toUser(Source source);
    /* I want to return a null user depending on a complex condition
    *  However, mapstruct ingores null value returned from the following @AfterMapping method
    * */
    
    @AfterMapping
    default User checkUser(@MappingTarget User user){
        // return null or not depending on a complex condition
        if(condition)
            return null;
        else return user;
    }
}

1 Answers1

0

You can use a decorator:

Official documentation: Customizing mappings with Decorator
StackOverflow similar question: mapstruct return null if condition is true

Paul Marcelin Bejan
  • 990
  • 2
  • 7
  • 14