DataAccessException is Spring’s unchecked base exception for data-access failures. When JdbcTemplate catches a JDBC SQLException, Spring translates it into an appropriate exception from this hierarchy, so repository methods need not declare it. section 12.2
When a database operation fails, choose how the application responds:
- Let the exception propagate to a service or presentation layer for logging and response handling; propagation also lets Spring roll back a transaction. section 12.2
- Catch a specific subclass when recovery or a more useful response is possible. A constraint violation might produce DataIntegrityViolationException; invalid SQL might produce BadSqlGrammarException. section 12.2
Listing 12.1 Plain JDBC code that works with data in a relational database
String sql = "INSERT INTO purchase VALUES (?,?)";
try (PreparedStatement stmt = con.prepareStatement(sql)) {
stmt.setString(1, name);
stmt.setDouble(2, price);
stmt.executeUpdate();
} catch (SQLException e) {
// do something when an exception occurs
}Compare plain JDBC’s explicit SQLException catch with JdbcTemplate’s exception translation. section 12.2
