mike mike - 10 days ago 5
Java Question

Custom mapper class is not getting the result?

I am writing one DAO application and i want to get zone data, I written my own mapper class, i connot able to get values. it is throwing exception.

Mapper class

public class zoneMapper implements RowMapper {

@Override
public Object mapRow(ResultSet resultSet, int rowNum) throws SQLException {

ZoneBean zone=new ZoneBean();
zone.setZoneId(resultSet.getInt("ZONE_ID"));
zone.setZoneName(resultSet.getString("ZONE_NAME"));
return zone;

}


dao call

List<ZoneBean> zoneList=new ArrayList<ZoneBean>();
try {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

zoneList = (List<ZoneBean>) jdbcTemplate.queryForObject(
queriesConstants.GET_ZONES, new zoneMapper());
}catch(Exception e){
System.out.println("getZones "+e.getMessage());
//logger.error("getZones "+e.getMessage());
}
**Exception is**
getZones Incorrect result size: expected 1, actual 17

Answer

getZones Incorrect result size: expected 1, actual 17

You retrieve multiple elements when your execute your query.

public <T> T queryForObject(String sql, RowMapper<T> rowMapper) is therefore not suitable for your need because it executes a query given static SQL, mapping a single result row to a Java object via a RowMapper.

You should use rather this method :

public <T> List<T> query(String sql, RowMapper<T> rowMapper)which executes a query given static SQL, mapping each row to a Java object via a RowMapper.