首页 > 解决方案 > mapstruct 如何将对象列表转换为接口列表?

问题描述

我有以下接口和类

public interface Fruit { ... }

public class AppleDto implements Fruit {...}

public class AppleEntity { ... }

我创建了一个映射器,它将Listof转换AppleEntityListofAppleDto但我需要返回类型为Listof Fruit

@Mapper
public interface FruitsMapper {
    FruitsMapper INSTANCE = Mappers.getMapper(FruitsMapper.class);

    @IterableMapping(elementTargetType = AppleDto.class)
    List<Fruit> entityToFruits(List<AppleEntity> entity);
}

它不允许我转换为接口列表并给出错误。有没有合适的方法来实现我所需要的?

标签: javalistmapstruct

解决方案


您需要在 和 之间定义一个映射方法,AppleEntityFruit通过以下方式定义结果类型@BeanMapping#resultType

在你的情况下,它看起来像:

@Mapper
public interface FruitsMapper {
    FruitsMapper INSTANCE = Mappers.getMapper(FruitsMapper.class);

    @BeanMapping(resultType = AppleDto.class)
    Fruit map(AppleEntity entity);

    List<Fruit> entityToFruits(List<AppleEntity> entity);
}

使用@IterableMapping#elementTargetType不是您所期望的。当有多种映射方法可能时,它只是一个选择标准。从它的javadoc:

Specifies the type of the element to be used in the result of the mapping method in case multiple mapping
methods qualify.

推荐阅读