liveBook · Manning

DataAccessException

As explained in Spring Start Here, Second Edition

DataAccessException is Spring's unchecked base exception type for data-access failures.

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

How Spring Start Here, Second Edition covers it

How deep it goes
Defines the unchecked hierarchy, names example subclasses, and explains handling choices without detailing translation internals.
Examples
Illustrates constraint violations and invalid SQL as causes of specific translated exceptions.
What you can do after
Apply exception handling by propagating failures or catching a specific subclass when recovery or a clearer response is appropriate.
How it connects
Connects JdbcTemplate and SQLException to DataIntegrityViolationException, BadSqlGrammarException, and transaction rollback.

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.