一穆役、問題場景
有兩個方法實現(xiàn)不同的 domain
到 entity
對象的轉(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)換方法添加標識政勃,然后在集合方法上添加對應(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) {
...
}
}