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

jio.jdbc.ResultSetMapper Maven / Gradle / Ivy

There is a newer version: 3.0.0-RC2
Show newest version
package jio.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

/**
 * A functional interface for mapping rows from a {@link java.sql.ResultSet} to objects of type {@code T}.
 *
 * @param > The entity produced by the result set mapper.
 */
@FunctionalInterface
public interface ResultSetMapper {


  /**
   * Mapper to handle a resul-set that contains at most one row. The `map` function doesn't have to call the `next`
   * method, just to collect the data from the column names.
   *
   * @param map      the map function (
   * @param  the type of the entity
   * @return the Entity
   */
  static  ResultSetMapper ONE_ROW(Function map) {
    return resultSet -> resultSet.next() ? map.apply(resultSet) : null;
  }

  /**
   * Creates a ResultSetMapper to handle a result set where each row represents an entity. The `map` function is called
   * for each row to collect entities into a list. The `next` method doesn't need to be called within the map function,
   * as it is automatically handled by this mapper.
   *
   * @param map      the map function to extract an entity from a result set row.
   * @param  the type of the entity.
   * @return a ResultSetMapper for handling one row per entity.
   */
  static  ResultSetMapper> ONE_ROW_PER_ENTITY(ResultSetMapper map) {
    return resultSet -> {
      List entities = new ArrayList<>();
      while (resultSet.next()) {
        entities.add(map.apply(resultSet));
      }
      return entities;
    };
  }


  /**
   * Applies the mapping function to the given {@code ResultSet} to produce an object of type {@code T}.
   *
   * @param resultSet The result set to map to an object.
   * @return An entity resulting from the mapping.
   * @throws SQLException if a failure happens while reading the ResultSet
   */
  Entity apply(ResultSet resultSet) throws SQLException;
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy