简体   繁体   中英

Mapstruct self defined mapper AND automatically generated one

I understand Mapstruct allows me to define my own mapper logic, I am doing it like this:

@Mapper(componentModel = "spring")
public abstract class ProjectMapper {

    public ProjectInfo map(ProjectEntity projectEntity) {
        ProjectInfo projectInfo = new ProjectInfo();
        projectInfo.setName(projectEntity.getName());
        projectInfo.setDescription(projectEntity.getDescription());

        // Specific logic that forces me to define it myself
        if (projectEntity.getId() != null) {
            projectInfo.setId(projectEntity.getId());
        }
        if (projectEntity.getOrganisation() != null) {
            projectInfo.setOrganisation(projectEntity.getOrganisation().getName());
        }
        return projectInfo;
    }
}

It works just fine, but I also want Mapstruct 's generated mappers, but they have to be defined in an interface, is there a way to group up both of these mapper types?

NOTE: Untested. I used the following solution once in a Spring-Boot project using MapStruct version 1.0.0.Final.

Customizing standard mapping process is fairly well documented .

One of the way to customize your mappings are 'AfterMapping' and 'BeforeMapping' hooks :

@Mapper
public abstract class ProjectMapperExtension {

    @AfterMapping
    public void mapProjectEntityToProjectInfo(ProjectEntity projectEntity, @MappingTarget ProjectInfo projectInfo) {

        if (projectEntity.getId() != null) {
            projectInfo.setId(projectEntity.getId());
        }

        if (projectEntity.getOrganisation() != null) {
            projectInfo.setOrganisation(projectEntity.getOrganisation().getName());
        }
    }
}

Then annotate the standard mapper interface with uses and exclude the custom mapped fields from the standard mapping:

@Mapper(componentModel = "spring", uses = {ProjectMapperExtension.class})
public interface ProjectMapper {

    @Mapping(target = "id", ignore = true)
    @Mapping(target = "organisation", ignore = true)
    ProjectInfo mapProjectEntityToProjectInfo(ProjectEntity projectEntity);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM