Search code examples
javaspringdatamappermapstruct

Map Only Particular Fields from DTO -> Model Using Map-Struct


I have use case where i need to map or fill data for particular fields

for example : I Have a user Model which i need to convert to UserDTO with only particular fields like username and accountId.

MODEL :

public class UserCore{

        private String accountId;

        private String username;
        private String workEmail;
        private String firstName;
        private String password;
        private String hashedPassword;

    }

UserDTO :

public class UserCoreDTO{

        private String accountId;

        private String username;
        private String workEmail;
        private String firstName;
        private String password;
        private String hashedPassword;

    }

is there any way in map-struct so that i can map only particular fields from source to destination

for example :

UserMapper mapper = Mappers.getMapper( UserMapper.class );
mapper.map(fieldsToFetch,source,destination);

Solution

  • Here's an example form the docs:

    @Mapper
    public interface FishTankMapper {
    
        @Mappings({
            @Mapping(target = "fish.kind", source = "fish.type"),
            @Mapping(target = "fish.name", ignore = true),
            @Mapping(target = "ornament", source = "interior.ornament"),
            @Mapping(target = "material.materialType", source = "material"),
            @Mapping(target = "quality.report.organisation.name", source = "quality.report.organisationName")
        })
        FishTankDto map( FishTank source );
    }
    

    ignore = true will probably work for all fields, not just nested fields as in the example.