javaspring-bootmapstruct

No method found annotated with @Named#value


I'm having trouble using MapStruct version 1.4.1 when I'm trying to implement my own mapping. This is code that I wrote:

package com.kucazdravlja.user.mappers;

import com.kucazdravlja.user.dto.NoticeBoardDto;
import com.kucazdravlja.user.entities.NoticeBoard;
import com.kucazdravlja.user.entities.NoticeBoardStatus;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;

import java.util.Objects;

@Mapper(uses = {BaseJournalMapper.class})
public interface NoticeBoardMapper {

    @Mapping(source = "status", target = "status", qualifiedByName = "getNoticeBoardStatusName")
    NoticeBoard dtoToEntity(NoticeBoardDto noticeBoardDto);

    @Mapping(source = "status", target = "status", qualifiedByName = "getNoticeBoardStatusDescription")
    NoticeBoardDto entityToDto(NoticeBoard noticeBoard);

    @Named("getNoticeBoardStatusDescription")
    static String getNoticeBoardStatusDescriptionConverter(NoticeBoard noticeBoard) {
        return Objects.requireNonNull(NoticeBoardStatus.findByName(noticeBoard.getStatus())).getDescription();
    }

    @Named("getNoticeBoardStatusName")
    static String getNoticeBoardStatusNameConverter(NoticeBoardDto noticeBoardDto) {
        return Objects.requireNonNull(NoticeBoardStatus.findByName(noticeBoardDto.getStatus())).name();
    }
}

When running application it crashes and gives error

Error:(15, 5) java: Qualifier error. No method found annotated with @Named#value: [ getNoticeBoardStatusName ].

Not sure what is the problem because I have that method with that name.


Solution

  • In your @Mapping annotation, you are telling mapstruct to use the field "status" as the source for the mapping. But the methods take NoticeBoard and NoticeBoardDto as parameters. You need to change the parameter type to whatever your status is. Assuming it is string:

    @Named("getNoticeBoardStatusName")
    default String getNoticeBoardStatusNameConverter(String status) {
        return Objects.requireNonNull(NoticeBoardStatus.findByName(status)).name();
    }
    

    Also, don't use static methods in mappers, use the default keyword instead.