工作时定义了三个类
class A
class B
class C
其中 class A extends B
然后定义了一个转换类
@Mapper
public interface AbcConverter {
AbcConverter INSTANCE = Mappers.getMapper(AbcConverter.class);
A toA(C c);
B toB(C c);
List<B> toBList(List<C> cList);
}
此时报出编译异常
在最后有一个网址
https://mapstruct.org/faq/#ambiguous
打开后看到
How to solve ambiguous methods
MapStruct tries various mechanisms to map a sourceproperty to a targetproperty when it cannot make a direct mapping. In order, MapStruct tries:
other mapping methods (inside the mapper, or via the uses relation). This concerns both hand-written methods and MapStruct generated methods
direct mapping (source type is directly assignable to target type)
type conversions (e.g. from int to String)
BuiltIn methods (see documentation on a list of supported methods)
2 step method, variant 1: target = methodY( methodX ( source ) )
2 step method, variant 2: target = methodY( conversionX ( source ) )
2 step method, variant 3: target = conversionY( methodX ( source ) )
Whenever MapStruct finds a unique candidate, MapStruct stops and uses this method to make the mapping between source and target. However, for option 1, 5, 6, 7 it is possible that multiple eligible candidtates are found for which MapStruct cannot decide which one to select. MapStruct reports this as “ambiguous mapping method” and lists the methods from which it cannot make a selection. Here, you have to guide MapStruct in making the correct mapping.
This can be done in the following ways:
provide a method with the exact signature if MapStruct cannot select between base- and super types.
provide qualifiers.
Problems with qualifiers
MapStruct uses the mechanism of Qualifiers to resolve conflicts. MapStruct selects methods based on the combination of source type and target type.
An error labeled: “Qualifier error” is MapStructs way of letting you know that it cannot find the method you intended to annotate with a qualifier annotation or with @Named. There can be several reasons for this:
you forgot to add the proper retention policy. It must be @Retention(RetentionPolicy.CLASS)
you forgot to add the qualifier (your own annotation, or @Named) to the designated method
the method signature to which you added the qualfier does not match the source type and target type required for the mapping
in 1.3.x and earlier, MapStruct was more lenient and allowed qualifiers also if MapStruct did not actually use them. That has been fixed in 1.4.x, on order to get consistent behaviour
if you wanted to use a 2 step mapping (so selecting two mapping methods) to get from source to target, you need to add the qualifier to both designated methods.
此时迭代器出现语意不明的情况
通过@IterableMapping指定迭代器转换方法
@Mapper
public interface AbcConverter {
AbcConverter INSTANCE = Mappers.getMapper(AbcConverter.class);
A toA(C c);
@Named("toB")
B toB(C c);
@IterableMapping(qualifiedByName = "toB")
List<B> toBList(List<C> cList);
}