MapStruct: Ambiguous mapping methods found for mapping collection element 問題解決

一、問題場景

有兩個方法實現(xiàn)不同的 domainentity 對象的轉(zhuǎn)換,也同時存在對應(yīng)的集合轉(zhuǎn)換的方法,大致代碼如下:

@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 異常。

二、解決方案

對不同的轉(zhuǎn)換方法添加標(biāo)識,然后在集合方法上添加對應(yīng)的引用,具體如下:

@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 重復(fù)解決

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

@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) {
        ...
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容