I am new to using MapStruct and thus facing some issues with the same.
I have the following Model classes :-
@Data
class User {
@Field
private String fullName;
@Field("experience")
private List<Experience> workExperience;
//other fields
}
@Data
class Experience {
private Date joiningDate;
//other fields
}
Now, I have the following DTO's
@Data
class UserDTO {
private String firstName;
private String lastName;
private List<ExperienceDTO> workExperience;
//other fields
}
@Data
class ExperienceDTO {
private String joiningDate;
//other fields
}
Have written the UserMapper Interface as :-
@Mapper(componentModel = "spring")
public interface UserMapper {
@Mappings({
@Mapping(target = "firstName",source = "fullName",
qualifiedByName = "firstNameExtractor"),
@Mapping(target = "lastName",source = "fullName",
qualifiedByName = "lastNameExtractor")
})
UserDTO userToUserDTO(User user);
@Mappings({
@Mapping(target = "joiningDate", source = "joiningDate",
dateFormat = "yyyy-MM-dd HH:mm:ss")
})
List<ExperienceDTO> experienceToExperienceDTO(List<Experience> experience);
@Named("firstNameExtractor")
public static String getFirstName(String name){
String[] nameParts = name.split(" ");
return nameParts[0];
}
//similarly have a lastNameExtractor
But I get the following errors :-
I know my design might be wrong, but I am intentionally doing it this way to understand how MapStruct works. Kindly anyone could help me to understand what mistake I am doing?
The first error is because MapStruct does not see Lombok annotated methods. Add the annotation processor to the build:
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${org.projectlombok.version}</version>
</path>
</annotationProcessorPaths>
The second is that you add @Mapping to the list of objects, not the object itself. Create a method, which map a single Experience to ExperienceDTO, add the annotation there and remove it from the experienceToExperienceDTO method.