kavetiraviteja
kavetiraviteja

Reputation: 2208

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);

Upvotes: 3

Views: 3401

Answers (1)

Alpar
Alpar

Reputation: 2897

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.

Upvotes: 1

Related Questions