Raw JDBC requires manually managing every step of database access: getting a connection, creating a statement, setting parameters, iterating a ResultSet, handling checked SQLExceptions, and closing resources in finally blocks. A simple query becomes 15+ lines of repetitive, error-prone boilerplate.
Spring JDBC Template provides a template-based API that eliminates JDBC boilerplate. JdbcTemplate wraps the JDBC workflow: it handles connection acquisition, statement creation, parameter binding, result extraction, and cleanup. Developers provide only the SQL and the logic to map results to objects.
- JdbcTemplate: Core class wrapping JDBC — execute query/update with automatic resource management
- NamedParameterJdbcTemplate: Uses named parameters (
:name) instead of positional (?) — more readable, especially with many parameters - RowMapper:
(ResultSet rs, int rowNum) → Tmaps a result set row to a domain object - ResultSetExtractor: For custom result extraction (e.g., building a Map from multiple rows)
- SQL scripts:
ResourceDatabasePopulatororScriptUtilsfor executing SQL scripts during testing or setup
- JdbcTemplate: Simplest template — positional
?parameters, automatic resource cleanup - NamedParameterJdbcTemplate: Named
:paramparameters, better readability, uses SqlParameterSource - SimpleJdbcTemplate (deprecated): Legacy wrapper, replaced by JdbcTemplate
- RowMapper: Maps individual rows — reusable, no external state
- ResultSetExtractor: Processes entire ResultSet (multiple rows, custom structures)
- SQL scripts: Execute SQL files via
ResourceDatabasePopulatorfor setup, testing, or migrations - PreparedStatementCallback: For full control over PreparedStatement creation and execution
- Built from: JDBC — JdbcTemplate is a wrapper over raw JDBC
- Built from: Spring Framework — JdbcTemplate is a Spring module for data access
- Contrasts with: Spring ORM — JdbcTemplate is direct SQL; Spring ORM is object-oriented
- Contrasts with: Spring Data JPA — JdbcTemplate gives SQL control; JPA abstracts SQL
- Related: Hibernate Query Language — Both execute database queries; HQL is ORM-based, JdbcTemplate is SQL-based
- Large results: JdbcTemplate fetches all results into memory by default — use
RowCallbackHandleror streaming for large datasets - No caching: Unlike ORM, JdbcTemplate has no built-in caching — each query hits the database
- No lazy loading: All fields must be explicitly selected; no proxy-based lazy loading
- SQL injection: Always use parameterized queries (
?or:param), never concatenate user input into SQL strings - DataSource configuration: JdbcTemplate needs a properly configured DataSource bean; Spring Boot auto-configures one