Reputation: 131
Given the Source class as defined below:
class Source{
private String name;
private int age;
private List<Phone> phones;
// getters and setters
}
and the Phone class as defined below:
class Phone{
private Long id;
private String phoneNumber;
// getters and setters
}
and the Target class as defined below:
class Target{
private String name;
private int age;
private List<Long> idsPhones;
// getters and setters
}
I have an interface is:
@Mapper
interface MyMapper{
Target toTarget(Source source);
Source toSource(Target target);
}
How can I map the List of Phones from the Source class to a List of idsPhones in the Target Class and vice versa?
Upvotes: 2
Views: 2456
Reputation: 21393
In order to achieve this you need to help MapStruct a bit by telling how to map from Phone
into Long
. And the reverse as well.
Your mapper needs to look something like:
@Mapper(uses = PhoneRepository.class)
interface MyMapper {
@Mapping(target = "idsPhones", source = "phones")
Target toTarget(Source source);
@InheritInverseMapping
Source toSource(Target target);
default Long fromPhone(Phone phone) {
return phone.getId();
}
}
If your PhoneRepository
contains a method that accepts a Long
and returns Phone
then MapStruct will automatically know what to do and invoke that method.
Upvotes: 2