Use JdbcTemplate’s update() method when SQL needs to change stored data. It executes INSERT, UPDATE, or DELETE statements and returns an update count. Pass the SQL statement and its parameter values; JdbcTemplate handles the JDBC work around it. section 12.2 section 12.5
Listing 12.6 Using JdbcTemplate to add a new record to a table
@Repository
public class PurchaseRepository {
private final JdbcTemplate jdbc;
public PurchaseRepository(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
public void storePurchase(Purchase purchase) { #A
String sql = #B
"INSERT INTO purchase (`product`, `price`) VALUES (?, ?)";
jdbc.update(sql, #C
purchase.getProduct(),
purchase.getPrice());
}
}The repository inserts a purchase by passing SQL and two values to update(). The question marks in the SQL are placeholders for the product and price. section 12.2
Behind the scenes, JdbcTemplate obtains a connection, creates a statement, and handles JDBC resources. It also catches SQLExceptions and translates them into unchecked DataAccessExceptions. Application code still needs to decide how to respond: let an exception propagate, or catch a specific subclass when recovery is possible. section 12.2
For retrieving rows with SELECT, use a JdbcTemplate query() method instead. A JdbcTemplate depends on a data source; Spring Boot can configure both automatically, while an application without Spring Boot can define them as beans. section 12.2 section 12.5
