Shiv
Shiv

Reputation: 201

mapstruct How to convert a list of object to list of interface?

I have below interface and classes

public interface Fruit { ... }

public class AppleDto implements Fruit {...}

public class AppleEntity { ... }

I have created a mapper, which converts List of AppleEntity to List of AppleDto but I need return type to be List of Fruit.

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

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

It's not allowing me to convert to list of interface and giving an error. Is there a proper way to achieve what I need?

Upvotes: 0

Views: 5136

Answers (1)

Filip
Filip

Reputation: 21393

You need to define a single mapping method between AppleEntity and Fruit and define the result type via @BeanMapping#resultType

In your case it will look like:

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

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

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

Using @IterableMapping#elementTargetType is not what you are expecting. It is just a selection criteria when there are multiple mapping methods possible. From it's javadoc:

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

Upvotes: 2

Related Questions