1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
51
52
53
54
55
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91 public List<ResultMapping> resolveWithConstructor() {
92 if (constructorResultMappings.isEmpty()) {
93
94 return constructorResultMappings;
95 }
96
97
98 final List<ConstructorMetaInfo> matchingConstructorCandidates = retrieveConstructorCandidates(
99 constructorResultMappings.size());
100
101 if (matchingConstructorCandidates.isEmpty()) {
102 return constructorResultMappings;
103 }
104
105
106 final Set<String> constructorArgsByName = constructorResultMappings.stream().map(ResultMapping::getProperty)
107 .filter(Objects::nonNull).collect(Collectors.toCollection(LinkedHashSet::new));
108
109
110 final boolean allMappingsHavePropertyNames = verifyPropertyNaming(constructorArgsByName);
111
112
113 if (allMappingsHavePropertyNames) {
114
115 removeCandidatesBasedOnParameterNames(matchingConstructorCandidates, constructorArgsByName);
116 }
117
118
119 final ConstructorMetaInfo matchingConstructorInfo = filterBasedOnType(matchingConstructorCandidates,
120 constructorResultMappings, allMappingsHavePropertyNames);
121 if (matchingConstructorInfo == null) {
122
123
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
133 return constructorResultMappings;
134 }
135 }
136
137
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
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
156
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
176 final ConstructorMetaInfo candidateInfo = candidateIterator.next();
177
178
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
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
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
262
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
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 }