Skip to content

Allow to use @Context parameter as a mapping source #3665

@Saljack

Description

@Saljack

Use case

We have this model:

class Model {
  List<Item> items;
  UUID modelId;
}

class Item {
  UUID itemId;
  String name;
}

class ItemDTO {
  UUID itemId;
  String name;
  UUID modelId;
}

Now we want map an instance of Model to List of ItemDTO. Se want to map the modelId field to each ItemDTO. We are not able to do it simply with Mapstruct:

@Mapping(source="items", target=".")
@Mapping(source="modelId", target=".")
List<ItemDTO> toDto(Model model)

This does not work and it is clear why. So we rewrite it like this:

default List<ItemDTO> toDto(Model model) {
  return toDto(model.getItems(), model.getModelId());
}

List<ItemDTO> toDto(List<Item> items, @Context UUID modelId);

@Mapping(source="modelId", target="modelId")
ItemDTO toDto(Item item, @Context UUID modelId);

But it does not work because @Context parameter cannot be used as a source. And it throws:

No property named "modelId" exists in source parameter(s). Did you mean "itemId"?

So it would be really useful to allow to use @Context parameters as a source. Mainly if you want to use the same value for all iterable.

Generated Code

No response

Possible workarounds

So we use one of these workarounds:

expression

@Mapping(target="modelId", expression = "java(modelId)")
ItemDTO toDto(Item item, @Context UUID modelId);

@AfterMapping

  @AfterMapping
  default void toDto(@MappingTarget ItemDTO target, Item item, @Context UUID modelId) {
    target.setModelId(modelId);
  }

MapStruct Version

MapStruct 1.6.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions