MapHandler.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.dbutils.handlers;

  18. import java.sql.ResultSet;
  19. import java.sql.SQLException;
  20. import java.util.Map;

  21. import org.apache.commons.dbutils.ResultSetHandler;
  22. import org.apache.commons.dbutils.RowProcessor;

  23. /**
  24.  * {@code ResultSetHandler} implementation that converts the first
  25.  * {@code ResultSet} row into a {@code Map}. This class is thread
  26.  * safe.
  27.  *
  28.  * @see org.apache.commons.dbutils.ResultSetHandler
  29.  */
  30. public class MapHandler implements ResultSetHandler<Map<String, Object>> {

  31.     /**
  32.      * The RowProcessor implementation to use when converting rows
  33.      * into Maps.
  34.      */
  35.     private final RowProcessor convert;

  36.     /**
  37.      * Creates a new instance of MapHandler using a
  38.      * {@code BasicRowProcessor} for conversion.
  39.      */
  40.     public MapHandler() {
  41.         this(ArrayHandler.ROW_PROCESSOR);
  42.     }

  43.     /**
  44.      * Creates a new instance of MapHandler.
  45.      *
  46.      * @param convert The {@code RowProcessor} implementation
  47.      * to use when converting rows into Maps.
  48.      */
  49.     public MapHandler(final RowProcessor convert) {
  50.         this.convert = convert;
  51.     }

  52.     /**
  53.      * Converts the first row in the {@code ResultSet} into a
  54.      * {@code Map}.
  55.      * @param resultSet {@code ResultSet} to process.
  56.      * @return A {@code Map} with the values from the first row or
  57.      * {@code null} if there are no rows in the {@code ResultSet}.
  58.      *
  59.      * @throws SQLException if a database access error occurs
  60.      *
  61.      * @see org.apache.commons.dbutils.ResultSetHandler#handle(java.sql.ResultSet)
  62.      */
  63.     @Override
  64.     public Map<String, Object> handle(final ResultSet resultSet) throws SQLException {
  65.         return resultSet.next() ? this.convert.toMap(resultSet) : null;
  66.     }

  67. }