Spring 5.0 Projects
上QQ阅读APP看书,第一时间看更新

Defining the RowMapper

As we are using the JDBC Template, we need a way to map the rows of data from a database to a Java object. This can be achieved by implementing a RowMapper interface. We will define mapper classes for all the three entities. For Country, the raw mapper class looks as follows:

public class CountryRowMapper implements RowMapper<Country>{

public Country mapRow(ResultSet rs, int rowNum)
throws SQLException {
Country country = new Country();
country.setCode(rs.getString("code"));
country.setName(rs.getString("name"));
country.setContinent(rs.getString("continent"));
country.setRegion(rs.getString("region"));
country.setSurfaceArea(rs.getDouble("surface_area"));
country.setIndepYear(rs.getShort("indep_year"));
country.setPopulation(rs.getLong("population"));
country.setLifeExpectancy(rs.getDouble("life_expectancy"));
country.setGnp(rs.getDouble("gnp"));
country.setLocalName(rs.getString("local_name"));
country.setGovernmentForm(rs.getString("government_form"));
country.setHeadOfState(rs.getString("head_of_state"));
country.setCode2(rs.getString("code2"));
if ( Long.valueOf(rs.getLong("capital")) != null ) {
City city = new City();
city.setId(rs.getLong("capital"));
city.setName(rs.getString("capital_name"));
country.setCapital(city);
}
return country;
}
}

Then we define the mapper class for City as follows:

public class CityRowMapper implements RowMapper<City>{
public City mapRow(ResultSet rs, int rowNum)
throws SQLException {
City city = new City();
city.setCountryCode(rs.getString("country_code"));
city.setDistrict(rs.getString("district"));
city.setId(rs.getLong("id"));
city.setName(rs.getString("name"));
city.setPopulation(rs.getLong("population"));
return city;
}
}

And finally, we define CountryLanguage as follows:

public class CountryLanguageRowMapper implements 
RowMapper<CountryLanguage> {
public CountryLanguage mapRow(ResultSet rs, int rowNum)
throws SQLException {
CountryLanguage countryLng = new CountryLanguage();
countryLng.setCountryCode(rs.getString("countrycode"));
countryLng.setIsOfficial(rs.getString("isofficial"));
countryLng.setLanguage(rs.getString("language"));
countryLng.setPercentage(rs.getDouble("percentage"));
return countryLng;
}
}