Quick revision
The short answer
JdbcTemplate does the repetitive and error-prone parts of JDBC for us: it gets and releases the connection, creates and closes statements, iterates the result set and calls our mapper for each row. It uses the connection bound to the current Spring transaction when there is one, and it translates SQLException into Spring's unchecked DataAccessException hierarchy, such as DuplicateKeyException. queryForObject throws EmptyResultDataAccessException when no row matches and IncorrectResultSizeDataAccessException when more than one does; NamedParameterJdbcTemplate adds :name parameters on top.
What to remember
In this answer, we saw that JdbcTemplate takes over the fixed steps of JDBC: getting and releasing connections, creating and closing statements, and iterating results, leaving us only the SQL, the parameters and a row mapper. It uses the connection bound to the current Spring transaction, translates SQLException into the unchecked, database-independent DataAccessException hierarchy, and its queryForObject throws EmptyResultDataAccessException for zero rows and IncorrectResultSizeDataAccessException for more than one. NamedParameterJdbcTemplate adds :name parameters and collection expansion.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
JdbcTemplate does the repetitive and error-prone parts of JDBC for us: it gets and releases the connection, creates and closes statements, iterates the result set and calls our mapper for each row. It uses the connection bound to the current Spring transaction when there is one, and it translates SQLException into Spring's unchecked DataAccessException hierarchy, such as DuplicateKeyException. queryForObject throws EmptyResultDataAccessException when no row matches and IncorrectResultSizeDataAccessException when more than one does; NamedParameterJdbcTemplate adds :name parameters on top.
Why this question is asked
JdbcTemplate is the class most Spring developers reach for when they need plain SQL, and its behaviour on empty results is a classic source of surprise exceptions in production. Interviewers ask this to check that we know what the template saves us from, how it fits into Spring transactions, and how its exceptions work. In this answer, we will compare plain JDBC with JdbcTemplate, see how it joins transactions, look at exception translation, deal with queryForObject's empty and multiple results, and meet NamedParameterJdbcTemplate.
1What Plain JDBC Makes Us Write
In plain JDBC, a simple lookup needs us to borrow a connection, prepare the statement, set parameters, execute, step through the result set, read each column, and close the result set, the statement and the connection, in the right order, even when something fails. We also have to catch the checked SQLException and decide what it means. The SQL and the mapping are maybe three lines; the rest is ceremony that is identical in every method and easy to get subtly wrong.
JdbcTemplate is Spring's answer, an example of the template method pattern: the template owns the fixed steps, and we supply only the parts that vary, the SQL, the parameters and a RowMapper that turns one row into an object.
Notice what is missing: no getConnection, no close, no try-with-resources, no checked exception. The template does all of that in a fixed order inside each call, so we cannot forget a step.
2How It Joins Spring Transactions
JdbcTemplate does not call dataSource.getConnection() directly. It asks DataSourceUtils for a connection, and DataSourceUtils first checks whether a Spring transaction has bound a connection to the current thread. If one has, the template uses it and does not close it afterwards, because the transaction manager owns it. If none has, it borrows a fresh connection from the pool for the call and returns it when the call ends.
8 messages in order. Play them, or step through them one at a time.
Outside a transaction, the same release step returns the connection to the pool.
That is why two JdbcTemplate calls inside one @Transactional method see each other's uncommitted changes and commit or roll back together, while the same two calls outside a transaction are independent auto-commit statements on possibly different connections. It also means that JdbcTemplate calls join a transaction started by JpaTransactionManager, as long as both use the same DataSource.
3Translating SQLException Into DataAccessException
When the database reports an error, the driver throws SQLException, which is checked and only tells us what went wrong through a SQLState code and a vendor error code. JdbcTemplate catches it and translates it with a SQLExceptionTranslator into a subclass of DataAccessException, Spring's unchecked hierarchy that is the same for every database.
So a unique constraint violation becomes DuplicateKeyException, a foreign key violation becomes DataIntegrityViolationException, a deadlock may become a subclass of PessimisticLockingFailureException, and a bad SQL statement becomes BadSqlGrammarException. Because the exceptions are unchecked, we only catch the ones we can handle, and because they are database-independent, the same catch works on PostgreSQL and MySQL.
4QueryForObject and the Empty Result
queryForObject is for queries that must return exactly one row. It reads the result into a list and checks the size. Zero rows throws EmptyResultDataAccessException; more than one throws IncorrectResultSizeDataAccessException. EmptyResultDataAccessException is itself a subclass of IncorrectResultSizeDataAccessException, with expected size 1 and actual size 0.
Notice the design choice: queryForObject treats an empty result as an error, because the method promises one object. When a missing row is normal, such as looking up by an id that may not exist, we use query and take the first element, or JdbcClient's optional(). Catching EmptyResultDataAccessException works but uses an exception for ordinary control flow.
5NamedParameterJdbcTemplate
With many parameters, question marks become hard to read and easy to put in the wrong order. NamedParameterJdbcTemplate wraps a JdbcTemplate and lets us write :name placeholders, filled from a Map or a SqlParameterSource. It rewrites them into question marks before calling JDBC, and it expands a Collection value into as many placeholders as the collection has elements, which makes IN lists easy.
In Spring Framework 6.1 and later, JdbcClient offers both styles through one fluent API, and it is built on the same machinery, so everything above about transactions and exception translation applies to it too.
6Follow-up questions
Is JdbcTemplate thread-safe?
Yes. Once configured, a JdbcTemplate holds only its DataSource and settings, and each call gets its own connection and statement, so one instance can be shared by every thread. In Spring Boot we simply inject the auto-configured bean.
How does Spring decide which DataAccessException to throw?
The default translator first looks at the SQLException's subclass, such as SQLIntegrityConstraintViolationException in JDBC 4, and at error codes listed for each database in Spring's sql-error-codes.xml, then falls back to SQLState classes. We can customise it by registering our own SQLExceptionTranslator, for example to map a custom database error code to our own exception.
Should we use queryForObject for a count query?
Yes, it is a good fit, because a count always returns exactly one row: jdbc.queryForObject("select count(*) from customer", Long.class). The empty-result exception can never happen there. It is for lookups by key, where a missing row is normal, that we prefer query or optional().
7Conclusion
In this answer, we saw that JdbcTemplate takes over the fixed steps of JDBC: getting and releasing connections, creating and closing statements, and iterating results, leaving us only the SQL, the parameters and a row mapper. It uses the connection bound to the current Spring transaction, translates SQLException into the unchecked, database-independent DataAccessException hierarchy, and its queryForObject throws EmptyResultDataAccessException for zero rows and IncorrectResultSizeDataAccessException for more than one. NamedParameterJdbcTemplate adds :name parameters and collection expansion.
Open with
JdbcTemplate removes the boilerplate of JDBC. With plain JDBC I have to get a connection, prepare the statement, set parameters, execute, loop over the result set, and close everything in the right order even on errors, plus handle a checked SQLException.
Then, if they want more
With JdbcTemplate I give it the SQL, the arguments and a RowMapper, and it does the rest: it gets the connection, creates and closes the statement, iterates the rows and calls my mapper for each one. It also participates in Spring transactions.
It gets its connection through DataSourceUtils, so inside a @Transactional method it uses the connection bound to that transaction and does not close it, which is why several calls commit or roll back together. Outside a transaction, each call borrows a connection and runs in auto-commit mode. The third big thing is exception translation.
It turns SQLException into Spring's unchecked DataAccessException hierarchy, which is the same for every database, so a unique violation becomes DuplicateKeyException and I can catch just that. For queryForObject, it expects exactly one row. If there are none it throws EmptyResultDataAccessException, and if there are several it throws IncorrectResultSizeDataAccessException; the first is a subclass of the second.
When a missing row is a normal case, I would use query and take the first element, or JdbcClient's optional, rather than catching the exception. And NamedParameterJdbcTemplate lets me use named parameters like :city, and expands collections for IN lists.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Framework 6
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.sql, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "What does JdbcTemplate do for you compared with plain JDBC, and what exception does...": https://scrivio-interview-library.netlify.app/databases/jdbc/d55d359ccb/