View Javadoc
1   /*
2    *    Copyright 2009-2023 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.executor;
17  
18  import java.lang.reflect.Array;
19  import java.util.List;
20  
21  import org.apache.ibatis.reflection.MetaObject;
22  import org.apache.ibatis.reflection.factory.ObjectFactory;
23  import org.apache.ibatis.session.Configuration;
24  
25  /**
26   * @author Andrew Gustafson
27   */
28  public class ResultExtractor {
29    private final Configuration configuration;
30    private final ObjectFactory objectFactory;
31  
32    public ResultExtractor(Configuration configuration, ObjectFactory objectFactory) {
33      this.configuration = configuration;
34      this.objectFactory = objectFactory;
35    }
36  
37    public Object extractObjectFromList(List<Object> list, Class<?> targetType) {
38      Object value = null;
39      if (targetType != null && targetType.isAssignableFrom(list.getClass())) {
40        value = list;
41      } else if (targetType != null && objectFactory.isCollection(targetType)) {
42        value = objectFactory.create(targetType);
43        MetaObject metaObject = configuration.newMetaObject(value);
44        metaObject.addAll(list);
45      } else if (targetType != null && targetType.isArray()) {
46        Class<?> arrayComponentType = targetType.getComponentType();
47        Object array = Array.newInstance(arrayComponentType, list.size());
48        if (arrayComponentType.isPrimitive()) {
49          for (int i = 0; i < list.size(); i++) {
50            Array.set(array, i, list.get(i));
51          }
52          value = array;
53        } else {
54          value = list.toArray((Object[]) array);
55        }
56      } else if (list != null && list.size() > 1) {
57        throw new ExecutorException("Statement returned more than one row, where no more than one was expected.");
58      } else if (list != null && list.size() == 1) {
59        value = list.get(0);
60      }
61      return value;
62    }
63  }