liveBook · Manning

JdbcTemplate update method

As explained in Spring Start Here, Second Edition

The JdbcTemplate update method executes a SQL statement that changes database data and returns an update count.

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

How Spring Start Here, Second Edition covers it

How deep it goes
Explains parameterized SQL, JDBC resource handling, and exception translation through a worked repository example.
Examples
Uses a purchase repository that inserts product and price values into a table.
What you can do after
Apply JdbcTemplate to insert a purchase using parameterized SQL.
How it connects
Connects JdbcTemplate to data sources, JDBC, DataAccessException, and query() methods.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.