在MapStruct映射后实现参数转换

时间:2019-08-07 08:52:35

标签: java mapstruct

我想使用MapStruct框架并扩展我映射的Java类。目前,我使用这个:

// @Mapper(config = BaseMapperConfig.class)
public interface MerchantsMapper {

    MerchantNewDTO toNewDTO(Merchants merchant);
}

自定义实现:

public MerchantNewDTO toNewDTO(Merchants merchant)
  {
    MerchantNewDTO merchantNewDTO = new MerchantNewDTO();

    merchantNewDTO.setId(Integer.valueOf(merchant.getId()));
    ......

    MerchantConfigurationUtils merchant_config = new MerchantConfigurationUtils();
    Map<MerchantConfigurationFeatureBitString, Boolean> features = merchant_config.initFromDatabaseValue(merchant.getSupported_features());

    merchantNewDTO.setSupports_api(features.get(MerchantConfigurationFeatureBitString.Supports_api));

    return merchantNewDTO;
  }

如您所见,我想获取getSupported_features并填充Supports_api值。

但是添加新值是非常痛苦的过程。有什么方法可以创建扩展映射接口并设置/获取值的适配器?

您能推荐一些解决方案吗?

1 个答案:

答案 0 :(得分:1)

您可以使用@AfterMapping@BeforeMapping来做到这一点。

@Mapper
public interface MerchantsMapper {

    @Mapping(target = "supports_api", ignore = "true")
    MerchantNewDTO toNewDTO(Merchant merchant);

    @AfterMapping
    default applyFeatures(@MappingTarget MerchatNewDTO merchantNewDTO, Merchant merchant) {

        MerchantConfigurationUtils merchant_config = new MerchantConfigurationUtils();
        Map<MerchantConfigurationFeatureBitString, Boolean> features = merchant_config.initFromDatabaseValue(merchant.getSupported_features());

        merchatNewDTO.setSupports_api(features.get(MerchantConfigurationFeatureBitString.Supports_api));
    }
}