gpt4 book ai didi

java - MapStruct 不复制子类属性

转载 作者:行者123 更新时间:2023-12-02 07:41:50 25 4
gpt4 key购买 nike

我有以下结构。我的子类中的属性不会复制到我的 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 DTOMapper
{
BaseSubDTO toDTO(final BaseClass entity);
}

行:

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

Controller 中的子类属性 subProperty1subProperty2 未映射到我的 BaseSubDTO

如何将子类属性映射到 DTO 中?

最佳答案

mapstruct 似乎尚不支持下转型映射。请参阅Support for Type-Refinement mapping (or Downcast Mapping)

为了保持通用,您可以实现一个自定义映射器来检查传入对象的类型:

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

用法:

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

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

希望有帮助。

关于java - MapStruct 不复制子类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56700386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com