Peter Penzov
Peter Penzov

Reputation: 1766

Implement params convert after MapStruct mapping

I want to use MapStruct framework and to extend the Java Class that I map. Currently I use this:

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

    MerchantNewDTO toNewDTO(Merchants merchant);
}

Custom implementation:

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;
  }

As you can see I want to get getSupported_features and to populate the Supports_api value.

But it's very painful process to add new values. Is there some way to create adapter which extends the mapped interface and set/get the values?

Can you recommend some solution?

Upvotes: 1

Views: 94

Answers (1)

Filip
Filip

Reputation: 21471

You could do this with @AfterMapping or @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));
    }
}

Upvotes: 1

Related Questions