M03 Q07 How does the JdbcTemplate support generic queries? How does it return objects and lists/maps of objects?
Jdbc Template supports generic queries with following methods:
queryForObject – returns single object, expects query to return only one record, if this requirement is not matched IncorrectResultSizeDataAccessException will be thrown
The first example of queryForObject will return one value which will be the employee's email as a string representation.
The next example of queryForObject finds an employee by id and it maps all columns to Employee.class using the custom mapper. Here we are not using generic type from Java. This is why a custom mapper needs to be provided to receive a custom type.
queryForList – returns a list of objects of the declared type, expects the query to return results with only one column, otherwise, IncorrectResultSetColumnCountException will be thrown
queryForMap – returns map for a single row with keys representing column names and values representing database record value, expects query to return only one record, if this requirement is not matched IncorrectResultSizeDataAccessException will be thrown
queryForRowSet – returns SqlRowSet object that contains metadata information (like column names) and allows to read results data and iterate through records. It comtains metadata and allows you to read data from it(getString(), getDate(), getInt()).
next() method allows you to move between different rows of ResultSet.
All the above methods have many versions and allow you to specify queries and parameters.
Jdbc Template returns objects, lists/map by using following:
- objects – queryForObject –
SingleColumnRowMapperfor generic types andRowMapperfor custom types - lists – queryForList –
SingleColumnRowMapperfor generic types - maps – queryForMap –
ColumnMapRowMapperfor any query