Mapstruct将一个字段映射到多个目标字段,反之亦然

时间:2018-09-16 23:44:12

标签: java spring-boot mapping mapstruct

我已经提到了问题Map multiple source fields to same type target fields with Mapstruct,但没有帮助

我的其余资源类如下

class Base {
//fields
//getters and setters
}

Class A extends Base{
List<String> emailAdddress;
//other fields
//getters and setters
}

Class B extends Base{
List<String> devices;
//other fields
//getters and setters
}

Class C extends Base{
List<String> mobileNumbers;
//other fields
//getters and setters
}

我的实体类是Source,如下所示:

 Class Source {
    String address
    //other fields
    //getters and setters
    }

我想在Source Map类中使用emailAdddress或设备或mobileNumbers映射Source类中的地址,我尝试在mapper类以及装饰类中使用@AfterMapping,但这没有帮助。

我有一个像这样的映射器类

@Mapper
public abstract class AddressMapper {
     //basic mappings here

public abstract Source toEntity(Base b);
public abstract Base toDomain(Source src);

   @AfterMapping 
   public void setAddressInfo(@MappingTarget Source src, B b) {
        src.setAddress(b.getDevices().toString());
}

1 个答案:

答案 0 :(得分:0)

我不确定我是否完全遵循您的尝试。

但是,如果要映射特定的类(ABC,则需要将它们放入方法中,因为MapStruct是注释处理器,在编译期间时间只知道示例中的Base字段。您可以执行以下操作:

@Maper
public interface AdressMapper {


    default Source toEntity(Base b) {
        if (b == null) {
            return null;
        } else if (b instanceOf A) {
            toEntity((A) b);
        } else if (b instanceOf B) {
            toEntity((A) b);
        } else if (b instanceOf C) {
            toEntity((C) b);
        } else {
            // Decide what to do
        }
    }

    @Mapping(target = "address", source = "emailAddress")
    Source toEntity(A a);

    @Mapping(target = "address", source = "devices")
    Source toEntity(B b);

    @Mapping(target = "address", source = "mobileNumbers")
    Source toEntity(C c);

    default Base toDomain(Source source) {
        if (source == null) {
            return null;
        } else if (condition to match to A) {
            return toDomainA(source);
        } else if (condition to match to B) {
            return toDomainB(source);
        } else if (condition to match to C) {
            return toDomainC(source);
        }
    }

    @Mapping(target = "emailAddress", source = "address")
    A toDomainA(Source source);

    @Mapping(target = "devices", source = "address")
    B toDomainB(Source source);

    @Mapping(target = "mobileNumbers", source = "address")
    C toDomainB(Source source);


    // This method is needed so MapStruct knows how to map from List<String> into String
    static <T> String listToString(List<T> list) {
        if (list == null) {
            return null;
        }

        return list.toString();
    }

    // This method is needed so MapStruct know hot to map from String into List<String>
    static List<String> fromListToString(String string) {
        if (string == null) {
            return null;
        }

        // Perform your own conversion
    }
}