001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.dbutils.handlers; 018 019import java.sql.ResultSet; 020import java.sql.SQLException; 021import java.util.Map; 022 023import org.apache.commons.dbutils.ResultSetHandler; 024import org.apache.commons.dbutils.RowProcessor; 025 026/** 027 * {@code ResultSetHandler} implementation that converts the first 028 * {@code ResultSet} row into a {@code Map}. This class is thread 029 * safe. 030 * 031 * @see org.apache.commons.dbutils.ResultSetHandler 032 */ 033public class MapHandler implements ResultSetHandler<Map<String, Object>> { 034 035 /** 036 * The RowProcessor implementation to use when converting rows 037 * into Maps. 038 */ 039 private final RowProcessor convert; 040 041 /** 042 * Creates a new instance of MapHandler using a 043 * {@code BasicRowProcessor} for conversion. 044 */ 045 public MapHandler() { 046 this(ArrayHandler.ROW_PROCESSOR); 047 } 048 049 /** 050 * Creates a new instance of MapHandler. 051 * 052 * @param convert The {@code RowProcessor} implementation 053 * to use when converting rows into Maps. 054 */ 055 public MapHandler(final RowProcessor convert) { 056 this.convert = convert; 057 } 058 059 /** 060 * Converts the first row in the {@code ResultSet} into a 061 * {@code Map}. 062 * @param resultSet {@code ResultSet} to process. 063 * @return A {@code Map} with the values from the first row or 064 * {@code null} if there are no rows in the {@code ResultSet}. 065 * 066 * @throws SQLException if a database access error occurs 067 * 068 * @see org.apache.commons.dbutils.ResultSetHandler#handle(java.sql.ResultSet) 069 */ 070 @Override 071 public Map<String, Object> handle(final ResultSet resultSet) throws SQLException { 072 return resultSet.next() ? this.convert.toMap(resultSet) : null; 073 } 074 075}