![]() |
VOOZH | about |
Understanding the difference between RowMapper and ResultSetExtractor is very important for anyone working with JDBC in Java. Both play important roles in fetching and processing data from the database. The main difference between RowMapper and ResultSetExtractor lies in their responsibilities.
The below table demonstrates the difference between RowMapper and ResultSetExtractor
Feature | RowMapper | ResultSetExtractor |
|---|---|---|
Scope | Maps a single row at a time | Processes the entire ResultSet |
Use Case | Simple row-to-object mapping | Complex ResultSet processing |
Flexibiltiy | Less flexible, simpler to use | More flexible, allows custom logic |
Method | mapRow(ResultSet rs, int rowNum) | extractData(ResultSet rs) |
Common Usage | Used with JdbcTemplate.query() | Used with JdbcTemplate.query() |
The RowMapper interface is designed to map a single row of a ResultSet to a Java object. It is used when the query returns multiple rows, and each row needs to be mapped to a corresponding object.
Example: This example demonstrates how to use a custom RowMapper (EmployeeRowMapper) with JdbcTemplate to map rows from a ResultSet to Employee objects.
The ResultSetExtractor interface is more flexible and powerful. It is designed to process the entire ResultSet at once, allowing for more complex mappings.
Example: This example demonstrates how to use a custom ResultSetExtractor (EmployeeResultSetExtractor) with JdbcTemplate to process the entire ResultSet and map multiple rows to a list of Employee objects.
Note: