javamapstruct

When I use MapStruct's qualifiedByName and @Named doesn't take effect


MapStruct version is 1.5.5.Final,JDK is 17,Here is my code

@Mapper
public interface UndoIssueConvert {
    UndoIssueConvert INSTANCE = Mappers.getMapper(UndoIssueConvert.class);

    @Mappings({
            @Mapping(target = "undoIssueId", source = "id"),
//          @Mapping(target = "createTime", expression = ("java(undoIssue.getUpdateTime() != null ? undoIssue.getUpdateTime() : undoIssue.getCreateTime())"))
            @Mapping(target = "createTime", qualifiedByName = "convertCreateTime")
    })
    UndoIssuePanelRspVO.UndoIssue toUndoIssue(UndoIssue undoIssue);

    List<UndoIssuePanelRspVO.UndoIssue> toUndoIssue(List<UndoIssue> undoIssue);

    @Named("convertCreateTime")
    default Date convertCreateTime(UndoIssue undoIssue) {
        return undoIssue.getUpdateTime() != null ? undoIssue.getUpdateTime() : undoIssue.getCreateTime();
    }

    UndoIssue toUndoIssueEntity(UndoIssueAddUpdateVO addVO);
}

But I get the following exception

java: Qualifier error. No method found annotated with @Named#value: [ convertCreateTime ]

I confirmed the annotation path is correct


Solution

  • The problem in your case is that the convertCreateTime method expects the entire UndoIssue object.

    Instead of passing the entire UndoIssue object to the convertCreateTime method, you must pass the required fields directly.

    Here is the solution way shown below

    Changed @Mapping(target = "createTime", qualifiedByName = "convertCreateTime") to @Mapping(target = "createTime", source = ".", qualifiedByName = "convertCreateTime")

    Here is the updated your code shown below

    @Mapper
    public interface UndoIssueConvert {
        UndoIssueConvert INSTANCE = Mappers.getMapper(UndoIssueConvert.class);
    
        @Mappings({
                @Mapping(target = "undoIssueId", source = "id"),
                @Mapping(target = "createTime", source = ".", qualifiedByName = "convertCreateTime")
        })
        UndoIssuePanelRspVO.UndoIssue toUndoIssue(UndoIssue undoIssue);
    
        List<UndoIssuePanelRspVO.UndoIssue> toUndoIssue(List<UndoIssue> undoIssue);
    
        @Named("convertCreateTime")
        default Date convertCreateTime(UndoIssue undoIssue) {
            return undoIssue.getUpdateTime() != null ? undoIssue.getUpdateTime() : undoIssue.getCreateTime();
        }
    
        UndoIssue toUndoIssueEntity(UndoIssueAddUpdateVO addVO);
    }