MapStruct mapping has boolean method

Mapstruct seen like only mapped the getXyz/setXyz/isXyz methods, if you ever have boolean method like hasNext, hasPrevious, that will be a problem. I’m facing this issues when tried to mapped the Spring Paged object. Lucky there is a solution for this, below is the sample openapi.yaml and the mapstruct code.

openapi.yaml

PagedResponse:
      type: object
      required:
        - pagination
      discriminator:
        propertyName: pagination
      properties:
        totalElements:
          type: integer
          format: int32
        totalPages:
          type: integer
          format: int32
        size:
          type: integer
          format: int32
        number:
          type: integer
          format: int32
        numberOfElements:
          type: integer
          format: int32
        pagination:
          type: string
        next:
          type: boolean

Here, we can use expression to defined the java method to tell mapstructs refer to hasNext method.

@Mapper(componentModel = MappingConstants.ComponentModel.SPRING, injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public interface QuizPagedResponseMappers {

    QuizPagedResponseMappers INSTANCE = Mappers.getMapper(QuizPagedResponseMappers.class);

    @Mapping(target = "totalPages", source = "totalPages")
    @Mapping(target = "next", expression = "java(paged.hasNext())" )
    QuizPagedResponse toResponse(Page paged);

}

Here is the generated file, as you can see the quizPagedResponse.next( paged.hasNext() ); now is using hasNext()

@Generated(
    value = "org.mapstruct.ap.MappingProcessor"
)
@Component
public class QuizPagedResponseMappersImpl implements QuizPagedResponseMappers {

    @Override
    public QuizPagedResponse toResponse(Page paged) {
        if ( paged == null ) {
            return null;
        }

        QuizPagedResponse quizPagedResponse = new QuizPagedResponse();

        quizPagedResponse.totalPages( paged.getTotalPages() );
        quizPagedResponse.totalElements( (int) paged.getTotalElements() );
        quizPagedResponse.size( paged.getSize() );
        quizPagedResponse.number( paged.getNumber() );
        quizPagedResponse.numberOfElements( paged.getNumberOfElements() );

        quizPagedResponse.next( paged.hasNext() );

        return quizPagedResponse;
    }
}

MapStruct mapping has boolean method

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.