Skip to content

Add Optional Support to JdbcTemplate [SPR-12662] #17262

Closed
@spring-projects-issues

Description

@spring-projects-issues

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 catching EmptyResultDataAccessException
  • 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:

Referenced from: pull request #724

13 votes, 15 watchers

Metadata

Metadata

Assignees

No one assigned

    Labels

    has: votes-jiraIssues migrated from JIRA with more than 10 votes at the time of importin: dataIssues in data modules (jdbc, orm, oxm, tx)status: declinedA suggestion or change that we don't feel we should currently applytype: enhancementA general enhancement

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions