Some doubts about RowMapper use in JDBC in a Spring Framework application

后端 未结 4 1632
悲哀的现实
悲哀的现实 2021-02-07 10:17

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

4条回答
  •  一生所求
    2021-02-07 11:01

    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.

提交回复
热议问题