Reputation: 2626
I have following entity class
public class Company {
private Map<Locale, String> name;
/* Other fields, getters, setters */
}
And the following DTO class
public class CompanyHeader {
private String name;
/* Other fields, getters, setters */
}
So, my entity contains names for different languages, and I want to map it for a given Locale
Here's my mapper class
@Mapper
public interface CompanyMapper {
CompanyHeader entityToHeader(Company company, Locale locale);
@Named("getByLocale")
default String getValueByLocale(Map<Locale, String> map, Locale locale) {
return map.get(locale);
}
}
And now my question is, how should I annotate my mapping method so that it understands company
as my source object, getValueByLocale
method as a mapping method for name
field, and locale
as a parameter for getValueByLocale
method?
Here's how I use my mapping method from outside
public Page<CompanyHeader> getCompanies(CompanyFilter companyFilter, Locale locale) {
Page<Company> companies = getCompanies(companyFilter);
Page<CompanyHeader> headers = companies.map(company -> companyMapper.entityToHeader(company, locale));
return headers;
}
Upvotes: 2
Views: 1851
Reputation: 21471
What you are trying to solve seems like a good usage for @Context
.
If you define your mapper like
@Mapper
public interface CompanyMapper {
CompanyHeader entityToHeader(Company company, @Coontext Locale locale);
default String getValueByLocale(Map<Locale, String> map, @Context Locale locale) {
return map.get(locale);
}
}
By using @Context
you are telling MapStrut that this object should not be seen as a mapping object and that it can be passed to other objects. With this method you are going to be able to map all Map<Locale, String>
properties into a String
.
You can read more about @Context
in the Passing context or state objects to custom methods
Upvotes: 1