001package com.randomnoun.common.spring; 002 003import java.sql.ResultSet; 004import java.sql.SQLException; 005import java.util.ArrayList; 006import java.util.List; 007 008import org.springframework.dao.DataAccessException; 009import org.springframework.jdbc.core.ResultSetExtractor; 010import org.springframework.jdbc.core.RowMapper; 011 012/** A ResultSetExtractor that uses a RowMapper to return a List of values from a ResultSet, but 013 * will not include nulls in the returned List. This could be used to return 014 * structured objects, where some records are used to modify existing results rather 015 * than returning new objects. 016 * 017 * @author knoxg 018 * 019 * @param <T> The type of object that the supplied RowMapper will return 020 */ 021public class SkipNullResultSetExtractor<T> implements ResultSetExtractor<List<T>> { 022 023 RowMapper<T> rowMapper; 024 025 public SkipNullResultSetExtractor(RowMapper<T> rowMapper) { 026 this.rowMapper = rowMapper; 027 } 028 029 @Override 030 public List<T> extractData(ResultSet rs) throws SQLException, DataAccessException { 031 List<T> results = new ArrayList<T>(); 032 int rowNum = 0; 033 while (rs.next()) { 034 T rowObj = (T) rowMapper.mapRow(rs, rowNum++); 035 if (rowObj!=null) { results.add(rowObj); } 036 } 037 return results; 038 } 039 040 041 042}