Skip to content

Introduce queryForOptional() method in JdbcTemplate #31644

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.stream.Stream;
Expand Down Expand Up @@ -912,6 +913,27 @@ public <T> T queryForObject(String sql, Class<T> requiredType, @Nullable Object.
return queryForObject(sql, args, getSingleColumnRowMapper(requiredType));
}

/**
* Query with the specified SQL statement, RowMapper, and optional arguments,
* returning the result as an Optional object. This method serves as a convenient substitution
* for the boilerplate code typically required when using queryForObject, especially
* to handle cases where the query result is empty.
*
* @param <T> The type of the result objects.
* @param sql The SQL statement to be executed.
* @param rowMapper The RowMapper implementation to map the query results to objects of type T.
* @param args Optional arguments to be bound to the SQL statement.
* @return An Optional containing the first result of the query, or an empty Optional if the
* query produced no results.
* @throws DataAccessException If an error occurs while accessing the data source.
*
* @see RowMapper
* @see Optional
*/
public <T> Optional<T> queryForOptional(String sql, RowMapper<T> rowMapper, @Nullable Object... args) throws DataAccessException {
return query(sql, rowMapper, args).stream().findFirst();
}

@Override
public Map<String, Object> queryForMap(String sql, Object[] args, int[] argTypes) throws DataAccessException {
return result(queryForObject(sql, args, argTypes, getColumnMapRowMapper()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;

Expand Down Expand Up @@ -436,4 +437,36 @@ public void testQueryForLongWithArgs() throws Exception {
verify(this.connection).close();
}

@Test
public void testQueryForOptionalWithArgsAndRowMapper() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = ?";
given(this.resultSet.next()).willReturn(true, false);
given(this.resultSet.getLong(1)).willReturn(87L);

Optional<Long> optionalResult = this.template.queryForOptional(sql, (rs, rowNum) -> rs.getLong(1), 1);

assertThat(optionalResult).as("Optional result").isPresent();
assertThat(optionalResult.get()).as("Correct result value").isEqualTo(87L);

verify(this.preparedStatement).setObject(1, 1);
verify(this.resultSet).close();
verify(this.preparedStatement).close();
verify(this.connection).close();
}

@Test
public void testQueryForOptionalWithArgsAndRowMapperEmptyResult() throws Exception {
String sql = "SELECT AGE FROM CUSTMR WHERE ID = ?";
given(this.resultSet.next()).willReturn(false);

Optional<Long> optionalResult = this.template.queryForOptional(sql, (rs, rowNum) -> rs.getLong(1), 2);

assertThat(optionalResult).as("Optional result").isEmpty();

verify(this.preparedStatement).setObject(1, 2);
verify(this.resultSet).close();
verify(this.preparedStatement).close();
verify(this.connection).close();
}

}