ResultExtractor.java

  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. import java.lang.reflect.Array;
  18. import java.util.List;

  19. import org.apache.ibatis.reflection.MetaObject;
  20. import org.apache.ibatis.reflection.factory.ObjectFactory;
  21. import org.apache.ibatis.session.Configuration;

  22. /**
  23.  * @author Andrew Gustafson
  24.  */
  25. public class ResultExtractor {
  26.   private final Configuration configuration;
  27.   private final ObjectFactory objectFactory;

  28.   public ResultExtractor(Configuration configuration, ObjectFactory objectFactory) {
  29.     this.configuration = configuration;
  30.     this.objectFactory = objectFactory;
  31.   }

  32.   public Object extractObjectFromList(List<Object> list, Class<?> targetType) {
  33.     Object value = null;
  34.     if (targetType != null && targetType.isAssignableFrom(list.getClass())) {
  35.       value = list;
  36.     } else if (targetType != null && objectFactory.isCollection(targetType)) {
  37.       value = objectFactory.create(targetType);
  38.       MetaObject metaObject = configuration.newMetaObject(value);
  39.       metaObject.addAll(list);
  40.     } else if (targetType != null && targetType.isArray()) {
  41.       Class<?> arrayComponentType = targetType.getComponentType();
  42.       Object array = Array.newInstance(arrayComponentType, list.size());
  43.       if (arrayComponentType.isPrimitive()) {
  44.         for (int i = 0; i < list.size(); i++) {
  45.           Array.set(array, i, list.get(i));
  46.         }
  47.         value = array;
  48.       } else {
  49.         value = list.toArray((Object[]) array);
  50.       }
  51.     } else if (list != null && list.size() > 1) {
  52.       throw new ExecutorException("Statement returned more than one row, where no more than one was expected.");
  53.     } else if (list != null && list.size() == 1) {
  54.       value = list.get(0);
  55.     }
  56.     return value;
  57.   }
  58. }