Spring JDBC: 返回 0 或 1 行

Spring JDBC: Returning 0 or 1 rows

我试过 google 这个问题,但找不到:Spring jdbcTemplate 中是否有推荐的方法,当我们期望返回 0 或 1 行时应该使用它。当没有行返回时,queryForObject() 将抛出异常。 queryForList() 将需要遍历列表,但这不是问题。但是很好奇是否有返回 0 或 1 行的 preferred/recommended 方法。谢谢!

您列出的选项是唯一可用的。至少在 Spring 中有 Optional 支持之前(参见 this bug report):

Add Optional Support to JdbcTemplate

From time to time I find myself working on queries that may return either one for no row. I 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

Java 8 Optionals are ideally suited for this problem.

我个人会使用 queryForList 并检查 isEmpty(),因为将逻辑放在 catch 中并不干净。

DataAccessUtils.singleResult(jdbcTemplate.queryForList(...));

我认为这正是为这些情况而设计的。如果集合为空,它 will return null 如果找到超过 1 个元素,则抛出 IncorrectResultSizeDataAccessException