【问题标题】:MapStruct: Mapping of Object classMapStruct:对象类的映射
【发布时间】:2020-07-03 22:42:32
【问题描述】:
Class Source {
   private String type;
   private Object identifier;
}

标识符可以是 AppointmentIdentifier 或 JobIdentifier 类的对象; 我必须将 Source 映射到 Target,它具有以下结构。

Class Target {
    private String type;
    private Object identifierBO;
}

标识符BO 可以是AppointmentIdentifierBO 或JobIdentifierBO 类的对象。 下面是我的 Mapper 类:

@Mapper
public interface ModelMapper {

    Target toTarget(@NonNull final Source source);

    AppointmentIdentifierBO toAppointmentIdentifierBO(AppointmentIdentifier appointmentIdentifier);

    JobBO toJobBO(JobIdentifier jobIdentifier);
}

我知道,我缺少一些有助于将标识符映射到标识符BO 的配置,但我无能为力。

【问题讨论】:

    标签: java mapstruct


    【解决方案1】:

    我只知道这样做的方法:

    @Mapper
    public interface ModelMapper {
        @Mapping(source = "identifier", target = "identifierBO", qualifiedByName = "identifierMapping")
        Target toTarget(Source source);
    
        @Named("identifierMapping")
        default Object mapIdentifier(Object obj) {
            if (obj instanceof AppointmentIdentifier)
                return toAppointmentIdentifierBO((AppointmentIdentifier) obj);
    
            if (obj instanceof JobIdentifier)
                return toJobBO((JobIdentifier) obj);
    
            throw new RuntimeException("Not supported type: " + obj.getClass());
        }
    
        AppointmentIdentifierBO toAppointmentIdentifierBO(AppointmentIdentifier appointmentIdentifier);
    
        JobBO toJobBO(JobIdentifier jobIdentifier);
    }
    

    可怕吗?是的。作品?是的。

    【讨论】:

    • 为什么可怕?如果您只有对象,则没有其他方法。这个答案很棒,一切都应该用 MapStruct (IMO) 完成
    • 感谢您的回答。我想过使用 @AfterMapping 函数和您在 mapIdentifier 中编写的相同代码。如果 MapStruct 能够理解 Object 的实例,那就太好了。
    • MapStruct 是一个注解处理器,它在运行时不做任何事情。因此,MapStruct 无法理解 Object 的实例。有一个类型优化请求 (github.com/mapstruct/mapstruct/issues/131)。但是,即使这样,我们也肯定不会查找所有可能的 Object 实例
    • @Shadov:代码不起作用,因为我收到了java.lang.RuntimeException: Not supported type: class java.util.LinkedHashMap。在 mapIdentifier 方法中,我通过 Jackson ObjectMapper 将 Object 转换为 AppointmentIdentifier。
    • 你当时没有使用 Jackson,基本上 Jackson 在无法转换为正确类型时转换为 LinkedHashMap。这看起来也很奇怪,你已经有一个Object,你为什么需要杰克逊? Jackson 支持String->Object 转换,反之亦然。提出单独的问题,链接在这里,我们会提供帮助。
    猜你喜欢
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 2016-10-14
    相关资源
    最近更新 更多