Reputation: 219
Consider the following POJOs:
public class PersonVo {
private String firstName;
private String lastName;
}
private class PersonEntity {
private String fullName;
}
Using MapStruct, I want create mapper that PersonVo
to PersonEntity
.
I need mapping multiple source fields firstName
, lastName
to one target filed fullName
.
Here is pseudo code what I want to.
[Want Solution A]
@Mapper
public interface PersonMapper {
@Mapping(target = "fullName", source = {"firstName", "lastName"}, qualifiedByName="toFullName")
PersonEntity toEntity(PersonVo person);
@Named("toFullName")
default String translateToFullName(String firstName, String lastName) {
return firstName + lastName;
}
}
[Want Solution B]
@Mapper
public interface PersonMapper {
@Mapping(target = "fullName", source = PersonVo.class, qualifiedByName="toFullName")
PersonEntity toEntity(PersonVo person);
@Named("toFullName")
default String translateToFullName(PersonVo pserson) {
return pserson.getFirstName() + pserson.getLastName();
}
}
Is there any way this can be achieved?
Upvotes: 3
Views: 15340
Reputation: 219
Here is my answer.
@Mapper
public interface PersonMapper {
@Mapping(target = "fullName", source = ".", qualifiedByName="toFullName")
PersonEntity toEntity(PersonVo person);
@Named("toFullName")
String translateToFullName(PersonVo pserson) {
return pserson.getFirstName() + pserson.getLastName();
}
}
Main point is that
@Mapping(target = "fullName", source = ".", qualifiedByName="toFullName")
It can make use source object by parameter.
Upvotes: 18
Reputation: 594
First I would go with public abstract class for Mappers. Makes it easier to extend them and create inheritance between the generated code and the abstract class. But here is your solution: You can achieve this by creating a @AfterMapping annotated method. So something like
@AfterMapping
default void concat(@MappingTarget PersonEntity person, PersonVo person) {
... manipulate the target value
}
Upvotes: 0