Description
Philippe Marschall opened SPR-12662 and commented
Problem
From time to time we find ourselves working on queries that may return either one for no row. We feel this situation is currently not well addressed with JdbcTemplate
. Current options include:
- using
#queryForObject
and catchingEmptyResultDataAccessException
- using
#query
or#queryForList
and checking the size of the list
Both of them feel rather cumbersome.
Proposal
We feel Java 8 Optionals are ideally suited for this problem. We therefore propose to add new queryForOptional
methods with the following behaviour
- no row: empty Optional
- one row: present Optional
- NULL: empty Optional
- more than one row: IncorrectResultSizeDataAccessException
We feel these semantics are natural match for Optional
. Mapping both no row and SQL NULL
to an empty Optional
may be a bit surprising at first however an Optional
can not contain Java null
and returning Java null
would seem against the sprit of Optional
. We feel the name fits well into the existing naming pattern and gives users a clear indication of the behaviour to expect without having to read the Javadoc first.
As the master in now on 5 which has a minimum of Java 8 these can be added directly to JdbcTemplate
.
Issue Links:
- Add iterable JDBC template to process large amount of data [SPR-13900] #18474 Add iterable JDBC template to process large amount of data
- Customize PreparedStatementCreatorFactory in getPreparedStatementCreator [SPR-16050] #20599 Customize PreparedStatementCreatorFactory in getPreparedStatementCreator
Referenced from: pull request #724
13 votes, 15 watchers