mapstruct does not copy Subclass properties into DTO

Saravana Kumar M :

I have the below structure. And the properties from my subclass are not getting copied to my DTO.

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
class BaseClass
{
 private Integer baseProperty1;
 private Integer baseProperty2;
 //getters & setters
}


class SubClass extends BaseClass
{
 private Integer subProperty1;
 private Integer subProperty2;
 //getters & setters
}

class BaseSubDTO
{
 private Integer baseProperty1;
 private Integer baseProperty2;
 private Integer subProperty1;
 private Integer subProperty2;
 //getters & setters
}

class BaseClassService
{
 public BaseClass find()
 {
  return baseClassRepository.findById(101);
 }
}

class BaseClassController
{
 public BaseSubDTO find()
 {
  return mapper.toDTO(baseClassService.find());
 }
}

@Mapper(componentModel = "spring")
public interface Mapper
{
    BaseSubDTO toDTO(final BaseClass entity);
}

The line:

return mapper.toDTO(baseClassService.find());

in the controller does not map the subclass properties subProperty1, subProperty2 to my BaseSubDTO.

Any help is appreciated. Thanks in Advance.

b0gusb :

It seems that Downcast Mapping is not supported yet in mapstruct. See Support for Type-Refinement mapping (or Downcast Mapping)

In order to keep things generic, you could implement a custom mapper that checks the type of the passed in object:

@Mapper
public interface ToDTOMapper {
    ToDTOMapper MAPPER = Mappers.getMapper(ToDTOMapper.class);

    BaseSubDTO toDTOFromBaseClass(BaseClass baseClass);

    BaseSubDTO toDTOFromSubClass(SubClass baseClass);

    default BaseSubDTO map(BaseClass baseClass) {
        if(baseClass instanceof SubClass) {
            return toDTOFromSubClass((SubClass)baseClass);
        } 
        return toDTOFromBaseClass(baseClass);
    }
}

usage:

SubClass subClass = ...
BaseClass baseClass = ...

ToDTOMapper mapper = ToDTOMapper.MAPPER;
BaseSubDTO dto = mapper.map(subClass);
dto = mapper.map(baseClass);

Hope that helps.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=123283&siteId=1
dto