一、问题场景
有两个方法实现不同的 domain
到 entity
对象的转换,也同时存在对应的集合转换的方法,大致代码如下:
@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) {
...
}
}