All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.arakelian.jdbc.handler.AbstractKeyedHandler Maven / Gradle / Ivy

The newest version!
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arakelian.jdbc.handler;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Map;

public abstract class AbstractKeyedHandler implements ResultSetHandler> {
    /**
     * Row handler
     */
    private final ResultSetHandler rowHandler;

    public AbstractKeyedHandler(final ResultSetHandler rowHandler) {
        if (rowHandler == null) {
            throw new IllegalArgumentException();
        }
        this.rowHandler = rowHandler;
    }

    public final ResultSetHandler getRowHandler() {
        return rowHandler;
    }

    /**
     * Convert each row's columns into a Map and store then in a Map under
     * ResultSet.getObject(key) key.
     *
     * @param rs
     *            ResultSet to process.
     * @return A Map, never null.
     * @throws SQLException
     *             if a database access error occurs
     */
    @Override
    public Map handle(final ResultSet rs, final ResultSetMetaData rsmd) throws SQLException {
        final Map result = createMap();
        for (;;) {
            final V row = rowHandler.handle(rs, rsmd);
            if (rowHandler.wasLast(row)) {
                break;
            }
            result.put(createKey(rs), row);
        }
        return result;
    }

    @Override
    public boolean wasLast(final Map result) {
        // handle method always exhausts ResultSet
        return true;
    }

    /**
     * This factory method is called by handle() to retrieve the key value from the
     * current ResultSet row.
     *
     * @param rs
     *            ResultSet to create a key from
     * @return K from the configured key column name/index
     * @throws SQLException
     *             if a database access error occurs
     */
    protected abstract K createKey(ResultSet rs) throws SQLException;

    protected abstract Map createMap();
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy