View Javadoc
1   /*
2    *    Copyright 2009-2025 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       https://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package org.apache.ibatis.builder;
17  
18  import java.lang.annotation.Annotation;
19  import java.lang.reflect.Constructor;
20  import java.util.ArrayList;
21  import java.util.Arrays;
22  import java.util.Iterator;
23  import java.util.LinkedHashMap;
24  import java.util.LinkedHashSet;
25  import java.util.List;
26  import java.util.Map;
27  import java.util.Objects;
28  import java.util.Set;
29  import java.util.stream.Collectors;
30  
31  import org.apache.ibatis.annotations.Param;
32  import org.apache.ibatis.logging.Log;
33  import org.apache.ibatis.logging.LogFactory;
34  import org.apache.ibatis.mapping.ResultMapping;
35  import org.apache.ibatis.reflection.ParamNameUtil;
36  import org.apache.ibatis.session.Configuration;
37  import org.apache.ibatis.type.TypeHandler;
38  import org.apache.ibatis.type.UnknownTypeHandler;
39  
40  public class ResultMappingConstructorResolver {
41  
42    private static final Log log = LogFactory.getLog(ResultMappingConstructorResolver.class);
43  
44    private final Configuration configuration;
45    private final List<ResultMapping> constructorResultMappings;
46    private final Class<?> resultType;
47    private final String resultMapId;
48  
49    /**
50     * @param configuration
51     *          the global configuration object
52     * @param constructorResultMappings
53     *          the current mappings as resolved from xml or annotations
54     * @param resultType
55     *          the result type of the object to be built
56     */
57    public ResultMappingConstructorResolver(Configuration configuration, List<ResultMapping> constructorResultMappings,
58        Class<?> resultType, String resultMapId) {
59      this.configuration = configuration;
60      this.constructorResultMappings = Objects.requireNonNull(constructorResultMappings);
61      this.resultType = Objects.requireNonNull(resultType);
62      this.resultMapId = resultMapId;
63    }
64  
65    /**
66     * Attempts to find a matching constructor for the supplied {@code resultType} and (possibly unordered mappings) by:
67     * <ol>
68     * <li>Finding constructors with the same amount of arguments</li>
69     * <li>Rejecting candidates which have different argument names than our mappings</li>
70     * <li>Ensuring the type of each mapping matches the resolved constructor</li>
71     * <li>Rebuilding and sorting the mappings according to the found constructor</li>
72     * </ol>
73     * <p>
74     * Note that if there are multiple constructors which match, {@code javaType} is the only way to differentiate between
75     * them. i.e. if there is only one constructor, all types could be missing, however if there is more than one with the
76     * same amount of arguments, we need type on at least a few mappings to differentiate and select the correct
77     * constructor.
78     * <p>
79     * Argument order can only be derived if all mappings have a {@code name} specified, as this is the only way we order
80     * against the constructor reliably, i.e. we cannot order {@code X(String, String, String)} based on types alone.
81     *
82     * @return ordered mappings based on the resolved constructor, original mappings if none were found, or original
83     *         mappings if they did not have property names and a constructor could not be resolved
84     *
85     * @throws BuilderException
86     *           when a constructor could not be resolved
87     *
88     * @see <a href="https://github.com/mybatis/mybatis-3/issues/2618">#2618</a>
89     * @see <a href="https://github.com/mybatis/mybatis-3/issues/721">#721</a>
90     */
91    public List<ResultMapping> resolveWithConstructor() {
92      if (constructorResultMappings.isEmpty()) {
93        // todo: AutoMapping works during runtime, we cannot resolve constructors yet
94        return constructorResultMappings;
95      }
96  
97      // retrieve constructors & trim selection down to parameter length
98      final List<ConstructorMetaInfo> matchingConstructorCandidates = retrieveConstructorCandidates(
99          constructorResultMappings.size());
100 
101     if (matchingConstructorCandidates.isEmpty()) {
102       return constructorResultMappings;
103     }
104 
105     // extract the property names we have
106     final Set<String> constructorArgsByName = constructorResultMappings.stream().map(ResultMapping::getProperty)
107         .filter(Objects::nonNull).collect(Collectors.toCollection(LinkedHashSet::new));
108 
109     // arg order can only be 'fixed' if all mappings have property names
110     final boolean allMappingsHavePropertyNames = verifyPropertyNaming(constructorArgsByName);
111 
112     // only do this if all property mappings were set
113     if (allMappingsHavePropertyNames) {
114       // while we have candidates, start selection
115       removeCandidatesBasedOnParameterNames(matchingConstructorCandidates, constructorArgsByName);
116     }
117 
118     // resolve final constructor by filtering out selection based on type info present (or missing)
119     final ConstructorMetaInfo matchingConstructorInfo = filterBasedOnType(matchingConstructorCandidates,
120         constructorResultMappings, allMappingsHavePropertyNames);
121     if (matchingConstructorInfo == null) {
122       // [backwards-compatibility] (we cannot find a constructor),
123       // but this used to get thrown ONLY when property mappings have been set
124       if (allMappingsHavePropertyNames) {
125         throw new BuilderException("Error in result map '" + resultMapId + "'. Failed to find a constructor in '"
126             + resultType.getName() + "' with arg names " + constructorArgsByName
127             + ". Note that 'javaType' is required when there is ambiguous constructors or there is no writable property with the same name ('name' is optional, BTW). There is more info in the debug log.");
128       } else {
129         if (log.isDebugEnabled()) {
130           log.debug("Constructor for '" + resultMapId + "' could not be resolved.");
131         }
132         // return un-modified original mappings
133         return constructorResultMappings;
134       }
135     }
136 
137     // only rebuild (auto-type) if required (any types are unidentified)
138     final boolean autoTypeRequired = constructorResultMappings.stream().map(ResultMapping::getJavaType)
139         .anyMatch(mappingType -> mappingType == null || Object.class.equals(mappingType));
140     final List<ResultMapping> resultMappings = autoTypeRequired
141         ? autoTypeConstructorMappings(matchingConstructorInfo, constructorResultMappings, allMappingsHavePropertyNames)
142         : constructorResultMappings;
143 
144     if (allMappingsHavePropertyNames) {
145       // finally sort them based on the constructor meta info
146       sortConstructorMappings(matchingConstructorInfo, resultMappings);
147     }
148 
149     return resultMappings;
150   }
151 
152   private boolean verifyPropertyNaming(Set<String> constructorArgsByName) {
153     final boolean allMappingsHavePropertyNames = constructorResultMappings.size() == constructorArgsByName.size();
154 
155     // If property names have been partially specified, throw an exception, as this case does not make sense
156     // either specify all names and (optional random order), or type info.
157     if (!allMappingsHavePropertyNames && !constructorArgsByName.isEmpty()) {
158       throw new BuilderException("Error in result map '" + resultMapId
159           + "'. We do not support partially specifying a property name nor duplicates. Either specify all property names, or none.");
160     }
161 
162     return allMappingsHavePropertyNames;
163   }
164 
165   List<ConstructorMetaInfo> retrieveConstructorCandidates(int withLength) {
166     return Arrays.stream(resultType.getDeclaredConstructors())
167         .filter(constructor -> constructor.getParameterTypes().length == withLength).map(ConstructorMetaInfo::new)
168         .collect(Collectors.toList());
169   }
170 
171   private static void removeCandidatesBasedOnParameterNames(List<ConstructorMetaInfo> matchingConstructorCandidates,
172       Set<String> constructorArgsByName) {
173     final Iterator<ConstructorMetaInfo> candidateIterator = matchingConstructorCandidates.iterator();
174     while (candidateIterator.hasNext()) {
175       // extract the names (and types) the constructor has
176       final ConstructorMetaInfo candidateInfo = candidateIterator.next();
177 
178       // if all our param names contain all the derived names, keep candidate
179       if (!candidateInfo.isApplicableFor(constructorArgsByName)) {
180         if (log.isDebugEnabled()) {
181           log.debug("While resolving the constructor '" + candidateInfo + "', it was excluded from selection. "
182               + "' Required parameters: [" + constructorArgsByName + "] Actual: ["
183               + candidateInfo.constructorArgs.keySet() + "]");
184         }
185 
186         candidateIterator.remove();
187       }
188     }
189   }
190 
191   private static ConstructorMetaInfo filterBasedOnType(List<ConstructorMetaInfo> matchingConstructorCandidates,
192       List<ResultMapping> resultMappings, boolean allMappingsHavePropertyNames) {
193     ConstructorMetaInfo matchingConstructorInfo = null;
194     for (ConstructorMetaInfo constructorMetaInfo : matchingConstructorCandidates) {
195       boolean matchesType = true;
196 
197       for (int i = 0; i < resultMappings.size(); i++) {
198         final ResultMapping constructorMapping = resultMappings.get(i);
199         final Class<?> type = constructorMapping.getJavaType();
200         final ConstructorArg matchingArg = allMappingsHavePropertyNames
201             ? constructorMetaInfo.getArgByPropertyName(constructorMapping.getProperty())
202             : constructorMetaInfo.getArgByOriginalIndex(i);
203 
204         if (matchingArg == null) {
205           if (log.isDebugEnabled()) {
206             log.debug("While resolving the constructor '" + constructorMetaInfo + "', it was excluded from selection. "
207                 + "' Could not find constructor argument for mapping: [" + constructorMapping + "], available ["
208                 + constructorMetaInfo.constructorArgs + "]");
209           }
210 
211           matchesType = false;
212           break;
213         }
214 
215         // pre-filled a type, check if it matches the constructor
216         if (type != null && !Object.class.equals(type) && !type.equals(matchingArg.getType())) {
217           if (log.isDebugEnabled()) {
218             log.debug("While resolving the constructor '" + constructorMetaInfo + "', it was excluded from selection. "
219                 + "' Required mapping: [" + constructorMapping + "] does not match actual type: [" + matchingArg + "]");
220           }
221 
222           matchesType = false;
223           break;
224         }
225       }
226 
227       if (!matchesType) {
228         continue;
229       }
230 
231       if (matchingConstructorInfo != null) {
232         if (log.isDebugEnabled()) {
233           log.debug("While resolving the constructor '" + constructorMetaInfo + "', it was excluded from selection. "
234               + "Match already found! Ambiguous constructors [" + matchingConstructorInfo + "]");
235         }
236 
237         // multiple matches found, abort as we cannot reliably guess the correct one.
238         matchingConstructorInfo = null;
239         break;
240       }
241 
242       matchingConstructorInfo = constructorMetaInfo;
243     }
244 
245     return matchingConstructorInfo;
246   }
247 
248   private List<ResultMapping> autoTypeConstructorMappings(ConstructorMetaInfo matchingConstructorInfo,
249       List<ResultMapping> resultMappings, boolean allMappingsHavePropertyNames) {
250     final List<ResultMapping> adjustedAutoTypeResultMappings = new ArrayList<>(constructorResultMappings.size());
251     for (int i = 0; i < resultMappings.size(); i++) {
252       final ResultMapping originalMapping = resultMappings.get(i);
253       final ConstructorArg matchingArg = allMappingsHavePropertyNames
254           ? matchingConstructorInfo.getArgByPropertyName(originalMapping.getProperty())
255           : matchingConstructorInfo.getArgByOriginalIndex(i);
256 
257       final TypeHandler<?> originalTypeHandler = originalMapping.getTypeHandler();
258       final TypeHandler<?> typeHandler = originalTypeHandler == null
259           || originalTypeHandler.getClass().isAssignableFrom(UnknownTypeHandler.class) ? null : originalTypeHandler;
260 
261       // given that we selected a new java type, overwrite the currently
262       // selected type handler so it can get retrieved again from the registry
263       adjustedAutoTypeResultMappings.add(
264           new ResultMapping.Builder(originalMapping).javaType(matchingArg.getType()).typeHandler(typeHandler).build());
265     }
266 
267     return adjustedAutoTypeResultMappings;
268   }
269 
270   private static void sortConstructorMappings(ConstructorMetaInfo matchingConstructorInfo,
271       List<ResultMapping> resultMappings) {
272     final List<String> orderedConstructorParameters = new ArrayList<>(matchingConstructorInfo.constructorArgs.keySet());
273     resultMappings.sort((o1, o2) -> {
274       int paramIdx1 = orderedConstructorParameters.indexOf(o1.getProperty());
275       int paramIdx2 = orderedConstructorParameters.indexOf(o2.getProperty());
276       return paramIdx1 - paramIdx2;
277     });
278   }
279 
280   /**
281    * Represents a {@link Constructor} with parameter names and types
282    */
283   class ConstructorMetaInfo {
284 
285     final Map<String, ConstructorArg> constructorArgs;
286     final List<ConstructorArg> argsByIndex;
287 
288     private ConstructorMetaInfo(Constructor<?> constructor) {
289       final List<ConstructorArg> args = fromConstructor(constructor);
290 
291       this.constructorArgs = args.stream()
292           .collect(Collectors.toMap(ConstructorArg::getName, arg -> arg, (arg1, arg2) -> arg1, LinkedHashMap::new));
293       this.argsByIndex = new ArrayList<>(this.constructorArgs.values());
294     }
295 
296     boolean isApplicableFor(Set<String> resultMappingProperties) {
297       return resultMappingProperties.containsAll(constructorArgs.keySet());
298     }
299 
300     ConstructorArg getArgByPropertyName(String name) {
301       return constructorArgs.get(name);
302     }
303 
304     ConstructorArg getArgByOriginalIndex(int index) {
305       if (argsByIndex.isEmpty() || index >= argsByIndex.size()) {
306         return null;
307       }
308 
309       return argsByIndex.get(index);
310     }
311 
312     private List<ConstructorArg> fromConstructor(Constructor<?> constructor) {
313       final Class<?>[] parameterTypes = constructor.getParameterTypes();
314       final List<String> argNames = getArgNames(constructor);
315 
316       final List<ConstructorArg> constructorArgs = new ArrayList<>(argNames.size());
317       for (int i = 0; i < argNames.size(); i++) {
318         constructorArgs.add(new ConstructorArg(parameterTypes[i], argNames.get(i)));
319       }
320 
321       return constructorArgs;
322     }
323 
324     private List<String> getArgNames(Constructor<?> constructor) {
325       List<String> paramNames = new ArrayList<>();
326       List<String> actualParamNames = null;
327 
328       final Annotation[][] paramAnnotations = constructor.getParameterAnnotations();
329       int paramCount = paramAnnotations.length;
330       for (int paramIndex = 0; paramIndex < paramCount; paramIndex++) {
331         String name = null;
332         for (Annotation annotation : paramAnnotations[paramIndex]) {
333           if (annotation instanceof Param) {
334             name = ((Param) annotation).value();
335             break;
336           }
337         }
338 
339         if (name == null && configuration.isUseActualParamName()) {
340           if (actualParamNames == null) {
341             actualParamNames = ParamNameUtil.getParamNames(constructor);
342           }
343           if (actualParamNames.size() > paramIndex) {
344             name = actualParamNames.get(paramIndex);
345           }
346         }
347 
348         paramNames.add(name != null ? name : "arg" + paramIndex);
349       }
350 
351       return paramNames;
352     }
353 
354     @Override
355     public String toString() {
356       return "ConstructorMetaInfo{" + "args=" + constructorArgs + '}';
357     }
358   }
359 
360   static class ConstructorArg {
361     private final Class<?> type;
362     private final String name;
363 
364     private ConstructorArg(Class<?> type, String name) {
365       this.type = type;
366       this.name = name;
367     }
368 
369     public Class<?> getType() {
370       return type;
371     }
372 
373     public String getName() {
374       return name;
375     }
376 
377     @Override
378     public String toString() {
379       return "arg{" + "type=" + type.getName() + ", name='" + name + '\'' + '}';
380     }
381   }
382 }