【问题标题】:Mapstruct : abstract target class and concrete type based on discriminator fieldMapstruct:基于鉴别器字段的抽象目标类和具体类型
【发布时间】:2018-06-01 12:38:54
【问题描述】:

MapStruct 是否可以根据鉴别器属性确定抽象类/接口的具体类型?

想象一个目标抽象类CarEntity 有两个子类SUVCity 和一个源类CarDto 有一个鉴别器字段type 有两个枚举常量SUVCITY。你如何告诉 MapStruct 根据源类中鉴别器字段的值来选择具体的类?

方法签名通常是:

public abstract CarEntity entity2Dto(CarDto dto);

编辑

precision : CarDto 没有任何子类。

【问题讨论】:

    标签: java mapstruct


    【解决方案1】:

    如果我理解正确,这是目前不可能的。见#131

    实现您需要的方法是执行以下操作:

    @Mapper
    public interface MyMapper {
    
        default CarEntity entity2Dto(CarDto dto) {
            if (dto == null) {
                return null;
            } else if (dto instance of SuvDto) {
                return fromSuv((SuvDto) dto));
            } //You need to add the rest
        }
    
        SuvEntity fromSuv(SuvDto dto);
    }
    

    而不是做检查实例。您可以使用鉴别器字段。

    @Mapper
    public interface MyMapper {
    
        default CarEntity entity2Dto(CarDto dto) {
            if (dto == null) {
                return null;
            } else if (Objects.equals(dto.getDiscriminator(), "suv")) {
                return fromSuv(dto));
            } //You need to add the rest
       } 
    
        SuvEntity fromSuv(CarDto dto);
    }
    

    【讨论】:

    • 好吧,我知道这听起来很奇怪,但我正在处理 CarDto 没有任何子类的遗留代码,尽管 CarEntity 有。
    • 那么 check 的实例可以是任何你想要的。看看我更新的答案。
    猜你喜欢
    • 2018-01-18
    • 1970-01-01
    • 2019-03-05
    • 2011-03-09
    • 2011-08-05
    • 1970-01-01
    • 2019-12-26
    • 2016-10-03
    • 2011-03-31
    相关资源
    最近更新 更多