Home > Blockchain >  How to map a field in Object from within using MapStruct
How to map a field in Object from within using MapStruct

Time:10-12

Suppose I have an 'AtributeDTO' and its respective 'Attribute' entity. (Actual objects have a lot of fields). Notice, we don't want to include 'friends' field in Entity.

public class AttributesDTO {
  private string name;
  private TypeADTO details;
  private List<TypeBDTO> friends;
}

public class Attributes {
  private string name;
  private TypeA details;
}

Also, TypeADTO Class

public class TypeADTO  {
  private List<TypeBDTO> friends;
}

I've also created a mapper 'AttributeMapper'

public interface AttributeMapper {

  AttributesDTO toAttributesDTO(
      Attributes attributes);

  Attributes toAttributes(
      AttributesDTO attributesDTO);

}

Now, while converting Entity to DTO using 'toAttributesDTO' method, I want to update 'friends' in DTO using the 'friends' field inside 'details' within the same DTO.

I tried overriding the setter for 'details' in DTO, but ideally, this is not the right thing to do. I wonder if there's any other way to do it without having to implement the whole mapper.

CodePudding user response:

Maybe try doing this if you are storing details friends list in the friends list dto

friends.addAll(details.getFriends());

or

friends.setFriends(details.getFriends());

or if you are using builder then

 public AttributesDto toAttributesDTO(Attributes attributes {
            return AttributeDto.builder()
                    .name(attributes.getName())
                    .friends(attributes.getDetails().getFriends())
                     //or try which works
                    .friends(attributes.getDetails())
                    .build();
}
  • Related