JdbcTemplate is Spring’s JDBC abstraction for performing SQL operations against relational databases without the connections, statements, result sets, cleanup, and checked-exception handling required by raw JDBC. It lets a repository focus on the query and mapping logic. section 3.1 section 3.0
A typical JdbcTemplate repository follows this shape:
- Add Spring Boot’s JDBC starter and provide a database, such as an embedded H2 database for development. section 3.1.2
- Inject JdbcTemplate into a repository marked with @Repository. section 3.1.2
- Use query with SQL and a row-mapping method to turn ResultSet rows into domain objects. section 3.1.2
- Use update for inserts, passing values for SQL placeholders as method arguments. section 3.1.2
- Expose repository operations such as findAll, findById, and save to application components. section 3.1.2 section 3.1.2
Finding an ingredient
A repository can call jdbcTemplate.query("select id, name, type from Ingredient where id=?", this::mapRowToIngredient, id), then return the first result as an Optional. The mapper constructs Ingredient from the row’s id, name, and type columns. section 3.1 section 3.1.2
Listing 3.2 Querying a database with JdbcTemplate
private JdbcTemplate jdbcTemplate;
public Optional<Ingredient> findById(String id) {
List<Ingredient> results = jdbcTemplate.query(
"select id, name, type from Ingredient where id=?",
this::mapRowToIngredient,
id);
return results.size() == 0 ?
Optional.empty() :
Optional.of(results.get(0));
}
private Ingredient mapRowToIngredient(ResultSet row, int rowNum)
throws SQLException {
return new Ingredient(
row.getString("id"),
row.getString("name"),
Ingredient.Type.valueOf(row.getString("type")));
}
Compare the compact JdbcTemplate query with the raw JDBC version, which explicitly manages connections, statements, result sets, cleanup, and SQLException handling. section 3.1
