I am studying Core Spring certification, and I have some doubts about how Spring handles JDBC requests:
Therefore, I know that I can receive data from my database tables in various ways, depending on the type of data that I expect to receive:
1) A query for a simple type (like int, long or String): I use the queryForObject () method for the jdbcTemplate strong> class, something like this:
String sql = "SELECT count(*) FROM T_REWARD";
int rowsNumber = jdbcTemplate.queryForObject(sql, Integer.class);
So, to get a simple object as an int value, I use the queryForObject () method , passing it the sql stattment and the type of object that I expect to receive in the output from the method.
Well, that’s pretty simple, and I think that everything is in order.
2) A query for the entire row of the table placed in the Map object : so if I do not need a single value (which may be in one column of a specific row in the table or something like a preliminary example). I can use the queryForMap (..) and queryForList () methods as follows:
2.1) queryForMap () : I use it if I expect a single row placed in a single map object , where each column value is displayed in my map, something like:
String sql = "select * from T_REWARD where CONFIRMATION_NUMBER = ?";
Map<String, Object> values = jdbcTemplate.queryForMap(sql,confirmation.getConfirmationNumber());
2.2) queryForList(): , , . Map, Map . - :
String sql = "select * from PERSON";
return jdbcTemplate.queryForList(sql);
, .
ResultSet JdbcTemplate, .
, JdbcTemplate . ?
, Spring RowMapper ResultSet :
public interface RowMapper<T> {
T mapRow(ResultSet rs, int rowNum)
throws SQLException;
}
compoese , RestaurandRowMapper queryForObject():
public Restaurant findByMerchantNumber(String merchantNumber) {
String sql = "select MERCHANT_NUMBER, NAME, BENEFIT_PERCENTAGE, BENEFIT_AVAILABILITY_POLICY from T_RESTAURANT where MERCHANT_NUMBER = ?";
return jdbcTemplate.queryForObject(sql, new RestaurantRowMapper(), merchantNumber);
:
class RestaurantRowMapper implements RowMapper<Restaurant> {
public Restaurant mapRow(ResultSet rs, int i) throws SQLException {
return mapRestaurant(rs);
}
}
:
private Restaurant mapRestaurant(ResultSet rs) throws SQLException {
String name = rs.getString("NAME");
String number = rs.getString("MERCHANT_NUMBER");
Percentage benefitPercentage = Percentage.valueOf(rs.getString("BENEFIT_PERCENTAGE"));
Restaurant restaurant = new Restaurant(number, name);
restaurant.setBenefitPercentage(benefitPercentage);
restaurant.setBenefitAvailabilityPolicy(mapBenefitAvailabilityPolicy(rs));
return restaurant;
}
, , , .
: , queryForObject(), , , , (, Interger Long).
, (, Restaurant, Restaurand), , ( "" ), :
return jdbcTemplate.queryForObject(sql, new RestaurantRowMapper(), merchantNumber);
mapRow(),
class RestaurantRowMapper implements RowMapper<Restaurant> {
public Restaurant mapRow(ResultSet rs, int i) throws SQLException {
return mapRestaurant(rs);
}
}
, , Spring mapRow(), Restaurand, queryForObject() - . , .
? , ?