Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add @Source annotation to enable usage of mapping source object in qualifier methods #3477

Open
markostijak opened this issue Dec 18, 2023 · 0 comments

Comments

@markostijak
Copy link

Use case

In addition to #3323, it would also be beneficial to introduce something like the @Source annotation. This annotation should behave similarly to the @Context annotation but utilize the mapping source parameter instead.

One use-case for implementing this feature is to support the localization of entity attributes during the mapping process to DTOs. In such cases, localization keys are dynamic and are likely calculated based on entity IDs in combination with attribute names.

By combining the @Source annotation with a @SourcePropertyName, we could create an elegant solution. Utilizing the qualifiedBy method, we could map entities to DTOs while taking into account localized values.

Generated Code

Let this be our entity:

public class Book implements Identifiable<Long> {

    @Id
    private Long id;
    
    private String name;

    private String description;

    ...

}

Then, mapper could look like this:

@Mapper(
        componentModel = SPRING,
        uses = StringLocalizer.class
)
public interface BookMapper {

    @Mapping(target = "name", qualifiedBy = Localized.class)
    @Mapping(target = "description", qualifiedBy = Localized.class)
    BookDto mapToDto(Book book);

}

And here is the qualifier method:

@Component
@RequiredArgsConstructor
public class StringLocalizer {

    private final MessageSource messageSource;

    @Localized
    public String localize(String original, @Source Identifiable<?> source, @SourcePropertyName String propertyName) {
        String code = source.getClass().getSimpleName() + "." + source.getId() + "." + propertyName;
        return messageSource.getMessage(code, null, original, LocaleContextHolder.getLocale());
    }

}

Note: this is just an illustration how it could be used.

Possible workarounds

No response

MapStruct Version

No response

@filiphr filiphr added this to the Future planning milestone Dec 27, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants