spring-framework icon indicating copy to clipboard operation
spring-framework copied to clipboard

Add "queryForFirst" methods to JdbcTemplate for querying first row of ResultSet

Open quaff opened this issue 8 months ago • 6 comments

It's very common to get first row of ResultSet or null for empty ResultSet, for example JdbcStepExecutionDao::getLastStepExecution from Spring Batch, see https://github.com/spring-projects/spring-batch/pull/4798 for background.

We should call Statement::setMaxRows as hints (some legacy driver may not honer it) before executing, and only consume first row of the ResultSet. Not sure about the return type, @Nullable T or Optional<T> is better?

If this proposal is accepted, then Optional<T> first() should be added to JdbcClient.


  1. Why not queryForList ? It will load all rows into memory.

  2. Why not queryForObject ? It requires exactly one row, but the ResultSet may be empty, and there is no standard syntax to limit one row across all databases.

  3. Why not queryForStream().findFirst() ? The result stream need be closed explicitly, and maxRows is set for whole JdbcTemplate, we need specific 1 only for this query.

quaff avatar Mar 28 '25 02:03 quaff