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

com.jn.sqlhelper.common.resultset.RowMapperResultSetExtractor Maven / Gradle / Ivy

There is a newer version: 5.0.9
Show newest version
package com.jn.sqlhelper.common.resultset;

import com.jn.langx.util.Preconditions;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class RowMapperResultSetExtractor implements ResultSetExtractor> {
    private int offset = 0;
    private int expectedMaxRows = Integer.MAX_VALUE;
    private RowMapper mapper;

    public RowMapperResultSetExtractor(RowMapper rowMapper) {
        this(rowMapper, 0, Integer.MAX_VALUE);
    }

    public RowMapperResultSetExtractor(RowMapper rowMapper, int expectedMaxRows) {
        this(rowMapper, 0, expectedMaxRows);
    }

    public RowMapperResultSetExtractor(RowMapper rowMapper, int offset, int expectedMaxRows) {
        Preconditions.checkNotNull(rowMapper, "RowMapper is required");
        Preconditions.checkTrue(offset >= 0, "offset is zero at least");
        this.offset = offset;
        this.mapper = rowMapper;
        this.expectedMaxRows = expectedMaxRows;
        if (expectedMaxRows < 0) {
            this.expectedMaxRows = 0;
        }
    }


    @Override
    public List extract(ResultSet rs) throws SQLException {
        List results = (this.expectedMaxRows > 0 ? new ArrayList(16) : new ArrayList());
        int rowIndex = 0;

        if (expectedMaxRows > 0) {
            ResultSetMetaData rsMetaData = rs.getMetaData();
            ResultSetDescription resultSetDescription = new ResultSetDescription(rsMetaData);
            while (rs.next() && results.size() < expectedMaxRows) {
                if (rowIndex < offset) {
                    rowIndex++;
                    continue;
                }
                results.add(this.mapper.mapping(rs, rowIndex++, resultSetDescription));
            }
        }
        return results;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy