Spring JDBC中数据库操作出错时谁会抛出异常?
Who Throws Exceptions When Database Errors Occur in Spring JDBC?
Great question—this is one of those under-the-hood details that trips up even seasoned Spring developers. Let me break it down step by step:
- The initial error source: When a database issue (like invalid SQL, connection failures, or constraint violations) occurs, the underlying JDBC driver is the first to throw a checked
SQLException. - Spring's translation layer: Spring JDBC uses an
SQLExceptionTranslator(usually the defaultSQLErrorCodeSQLExceptionTranslatororSQLStateSQLExceptionTranslator) to convert that checkedSQLExceptioninto an unchecked, Spring-specificDataAccessExceptionsubclass. This design choice lets you avoid cluttering your code with mandatory try/catch blocks for every database operation. - The final exception thrower: The core Spring JDBC template classes—most commonly
JdbcTemplateorNamedParameterJdbcTemplate—are the ones that ultimately throw these translated exceptions. When you call methods likeupdate()orquery(), the template handles raw JDBC calls internally, catches the driver'sSQLException, runs it through the translator, and then propagates the Spring exception up to your application code.
For example, if you run a query against a non-existent table:
jdbcTemplate.query("SELECT * FROM non_existent_table", new BeanPropertyRowMapper<>(User.class));
The JDBC driver throws a SQLException, Spring translates it to BadSqlGrammarException, and JdbcTemplate throws that exception for your code to handle (or let propagate to a global exception handler).
One key note: You’ll only ever get a raw SQLException if you use low-level connection access (like JdbcTemplate.execute(ConnectionCallback)), in which case you’re responsible for handling it yourself.
内容的提问来源于stack exchange,提问作者Machacool
相关产品推荐
相关产品推荐

