MapStruct: Ambiguous mapping methods found for mapping collection element 问题解决

一、问题场景

有两个方法实现不同的 domainentity 对象的转换,也同时存在对应的集合转换的方法,大致代码如下:

@Mapper
public interface UserConverter {

    List<UserEntity> toEntityOne(List<User> userList);

    @Mappings({
        // 方案一
        ...
    })
    UserEntity toEntityOne(User user);


    List<UserEntity> toEntityTwo(List<User> userList);

    @Mappings({
        // 方案二
        ...
    })
    UserEntity toEntityTwo(User user);
}

编译时,会报 Ambiguous mapping methods found for mapping collection element 异常。

二、解决方案

对不同的转换方法添加标识,然后在集合方法上添加对应的引用,具体如下:

@Mapper
public interface UserConverter {

    @IterableMapping(qualifiedByName = "one")
    List<UserEntity> toEntityOne(List<User> userList);

    @Named("one")
    @Mappings({
        // 方案一
        ...
    })
    UserEntity toEntityOne(User user);


    @IterableMapping(qualifiedByName = "two")
    List<UserEntity> toEntityTwo(List<User> userList);

    @Named("two")
    @Mappings({
        // 方案二
        ...
    })
    UserEntity toEntityTwo(User user);
}

三、After 重复解决

方法和上面类似,只是使用不同的注解,如下:

@Mapper
public interface UserConverter {

    @BeanMapping(qualifiedByName = "one")
    @Mappings({
        // 方案一
        ...
    })
    UserEntity toEntityOne(User user);

    @Named("one")
    @AfterMapping
    default void toEntityOneAfter(User user, @MappingTarget UserEntity entity) {
        ...
    }


    @BeanMapping(qualifiedByName = "two")
    @Mappings({
        // 方案二
        ...
    })
    UserEntity toEntityTwo(User user);

    @Named("two")
    @AfterMapping
    default void toEntityTwoAfter(User user, @MappingTarget UserEntity entity) {
        ...
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容