Spring Boot mapstruct不调用枚举实现的自定义字符串?

gudnpqoy  于 2023-08-04  发布在  Spring
关注(0)|答案(1)|浏览(108)

我有一个名为InstanceTask的实体,它有一个名为TaskStatusEnum statusEnum字段,还有一个名为String statusString字段的DTO InstanceTaskDto
下面是TaskStatusEnum

@AllArgsConstructor
@Getter
public enum TaskStatusEnum {
    ACTIVE("En cours."),
    DONE("Traitée"),
    TO_DO("A faire");

    private final String value;
}

字符串
我尝试使用mapstructMap器从InstanceTaskDto.statusMap到InstanceTask.status

@Mappings({
        @Mapping(target = "status" , source = "status", qualifiedByName = "getTaskInstanceStatusEnum"),
})
InstanceTask toEntity (InstanceTaskDto  instanceTaskDto);
@Mappings({       
        @Mapping(target = "status", source = ".", qualifiedByName = "getInstanceTaskStatus"),
})
 InstanceTaskDto  toDto (InstanceTask   instanceTask);

@Named("getInstanceTaskStatus")
default String getInstanceTaskStatus(InstanceTask instanceTask) 
{
    if(instanceTask.getStatus() == null)
        return null;

    return instanceTask.getStatus().getValue();
}

@Named("getTaskInstanceStatusEnum")
default Enum<TaskStatusEnum> getTaskInstanceStatusEnum(InstanceTaskDto instanceTaskDto) 
{
    if(instanceTaskDto.getStatus() == null)
        return null;

    TaskStatusEnum statusEnum = TaskStatusEnum.TO_DO;

    for (TaskStatusEnum status : TaskStatusEnum.values()) {
        if (status.getValue().equals(instanceTaskDto.getStatus())) {
            statusEnum = status;
        }
    }

    return statusEnum;
}


我遇到的问题是,在生成的InstanceTaskMapperImpl中,getTaskInstanceStatusEnum没有被调用,而是toEntitystatus字段的实现:

@Override
public InstanceTask toEntity(InstanceTaskDto instanceTaskDto) 
{
        if ( instanceTaskDto == null ) {
            return null;
        }

        InstanceTask instanceTask = new InstanceTask();

        if ( instanceTaskDto.getStatus() != null ) {
            instanceTask.setStatus( Enum.valueOf( TaskStatusEnum.class, instanceTaskDto.getStatus() ) );
        }
       // other stuff //
       return instanceTask ;
}


在toDTO上,我的自定义方法被正确调用:

@Override
    public InstanceTaskDto toDto(InstanceTask instanceTask) {
        if ( instanceTask == null ) {
            return null;
        }

        InstanceTaskDtoBuilder instanceTaskDto = InstanceTaskDto.builder();

        instanceTaskDto.status( getInstanceTaskStatus( instanceTask ) );
        // other stuff //
        return instanceTaskDto ;
    }


要使toEntity实现使用我的getTaskInstanceStatusEnum而不是上面显示的默认实现,我必须做些什么?

  • 谢谢-谢谢
cwtwac6a

cwtwac6a1#

default Enum<TaskStatusEnum>...更改为default TaskStatusEnum...

相关问题