- Spring 5.0 Projects
- Nilang Patel
- 184字
- 2021-07-02 12:34:56
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;
}
}
推薦閱讀
- CorelDRAW X6 中文版圖形設計實戰(zhàn)從入門到精通
- Modern JavaScript Web Development Cookbook
- C++黑客編程揭秘與防范
- 5G承載網(wǎng)網(wǎng)絡規(guī)劃與組網(wǎng)設計
- Hands-On Full Stack Development with Spring Boot 2 and React(Second Edition)
- Spring Cloud微服務架構進階
- 面向物聯(lián)網(wǎng)的嵌入式系統(tǒng)開發(fā):基于CC2530和STM32微處理器
- 大話社交網(wǎng)絡
- OMNeT++與網(wǎng)絡仿真
- 新手易學:新手學淘寶開店
- 計算機網(wǎng)絡技術及應用
- React Cookbook
- 工業(yè)互聯(lián)網(wǎng)創(chuàng)新實踐
- Getting Started with Memcached
- AIoT應用開發(fā)與實踐