001package com.randomnoun.common.spring; 002 003/* (c) 2013 randomnoun. All Rights Reserved. This work is licensed under a 004 * BSD Simplified License. (http://www.randomnoun.com/bsd-simplified.html) 005 */ 006 007import java.sql.*; 008 009import org.springframework.dao.TypeMismatchDataAccessException; 010import org.springframework.jdbc.core.*; 011 012 013/** 014 * This class is intended to replace the standard RowMapper provided by Spring 015 * to return a List of Long objects (rather than a List of Maps). The 016 * queries executed by this rowMapper must therefore always evaluate to 017 * a single numeric column 018 * 019 * <p>This class can be used as in the following code fragment: 020 * 021 * <pre style="code"> 022 List longList = jt.query( 023 "SELECT DISTINCT lngId FROM tblCave " + 024 "WHERE txtSecretPassword = ? ", 025 new Object[] { "open sesame" }, 026 new RowMapperResultReader(new LongRowMapper() )); 027 * </pre> 028 * 029 * 030 * 031 * @author knoxg 032 */ 033public class LongRowMapper 034 implements RowMapper<Long> 035{ 036 037 038 039 /** 040 * Creates a new ClobRowMapper object. 041 */ 042 public LongRowMapper() 043 { 044 } 045 046 /** 047 * Returns a single Long representing this row. 048 * 049 * @param resultSet The resultset to map 050 * @param rowNumber The current row number 051 * 052 * @return a single object representing this row. 053 * 054 * @throws TypeMismatchDataAccessException if the first column of the resultset is not 055 * numeric. 056 */ 057 public Long mapRow(ResultSet resultSet, int rowNumber) 058 throws SQLException 059 { 060 Object value; 061 062 value = resultSet.getObject(1); 063 064 if (value == null) { 065 // just keep it as a null 066 return null; 067 } else if (value instanceof Number) { 068 return ((Number) value).longValue(); 069 } else { 070 throw new TypeMismatchDataAccessException( 071 "Expecting numeric value in column 1 of query (found " + 072 value.getClass().getName() + ")"); 073 } 074 } 075}