Skip to content

Strategy to check at runtime the null value with JSpecifiy #4105

Description

@pkernevez

Use case

We have field that are null at object creation but a never null right after.
Example the field Id or CreatedAt on an entity. The field are nullable but on the ReadDto these field are not null.

I would like to be able to check at runtime that the field is not null with Objects.requireNonNull(...). It could be a new strategy for the mapping.

It may be possible with something like that:
@Mapping(target = "createdAt", nullValueCheckStrategy = NullValueCheckStrategy.AT_RUNTIME)

Generated Code

Having:

    @Override
    public ChangeRequestReadSimpleDto toChangeRequestDto2(ChangeRequest cr) {
        ShiftRawId id = null;
        ChangeRequestTypeDto type = null;
        OffsetDateTime createdAt = null;
        
        id = toRawShiftId(Objects.requireNonNull(cr.getId()));
        type = convertEnum( cr.getType() );
        OffsetDateTime createdAt = toOffsetTime(Objects.requireNonNull(cr.getCreatedAt()));
        return new ChangeRequestReadSimpleDto(id, type, createdAt);
    }

Instead of:

    @Override
    public ChangeRequestReadSimpleDto toChangeRequestDto2(ChangeRequest cr) {
        ShiftRawId id = null;
        ChangeRequestTypeDto type = null;
        OffsetDateTime createdAt = null;
        
        id = toRawShiftId(cr.getId()); // Error cr.getId() is nullable
        type = convertEnum( cr.getType() );
        OffsetDateTime createdAt = toOffsetTime(cr.getCreatedAt()); // Error cr.getCreatedAt() is nullable
        return new ChangeRequestReadSimpleDto(id, type, createdAt);
    }

Possible workarounds

Define a custom mapping with the expression:

    @Mapping(target = "createdAt", expression = "java(toOffsetTime(java.util.Objects.requireNonNull(cr.getCreatedAt())))")

MapStruct Version

1.7.0.Beta2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions