首页 > 解决方案 > Mapstruct 将一个字段映射到多个目标字段,反之亦然

问题描述

我已经提到了使用 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
    }

我想在我的映射器类中使用 emailAddress 或 devices 或 mobileNumbers 映射 Source 类的地址,我尝试在映射器类和装饰器类中使用 @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());
}

标签: javaspring-bootmappingmapstruct

解决方案


我不确定我是否完全遵循您正在尝试做的事情。

但是,如果要映射特定类 ( A, BC则需要将它们放在方法中。由于 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
    }
}

推荐阅读