I am studying how to execute query on a database using JDBC in Spring Framework.
I am following this tutorial: http://www.tutorialspoint.com/spring/spring_jdbc_example.h
When you pass an instance of your RowMapper
to the JdbcTemplate
method
List students = jdbcTemplateObject.query(SQL, new StudentMapper());
The JdbcTemplate
depending on which method you called, will internally use the mapper with the result set it gets from the JDBC Connection to create an object of your requested type. For example, since you called JdbcTemplate#query(String, RowMapper)
, the method will use your String SQL to query the database and will loop through each "row" in the ResultSet
kind of like this:
ResultSet rs = ... // execute query
List students = ...// some list
int rowNum = 0;
while(rs.next()) {
Student student = rowMapper.mapRow(rs, rowNum);
students.add(student);
rowNum++;
}
return students;
So, Spring
's JdbcTemplate
method will use the RowMapper
you provide and call its mapRow
method to create the expected return object.
You might like to look at Martin Fowler's Data Mapper in conjunction with Table Data Gateway for an idea of how these things are distributed and provide low coupling.